中心文本在一个img的div中

时间:2015-01-20 00:47:33

标签: html css

我试图在图片中居中(水平和垂直)文本,但我不知道该怎么做。

vertical-align和text-align似乎不起作用,指定宽度和高度似乎也不会导致任何解决方案。

HTML:

<a href="#" class="fadeBlack">
<span class="blackBG">
    <p class="picDisc">TEST</p>
    <img src="http://www.mountainguides.com/photos/everest-south/c2_2011b.jpg" width=100% height=100%>
</span>

CSS:

.photoGallery img {
background: #181818 no-repeat;
border-radius: 10px;
}
.blackBG {
display: inline-block;
background: #000000;
border-radius: 10px;
}
.picDisc {
position: absolute;
vertical-align: middle;
text-align: center;
}
a.fadeBlack img {
display: block;
-webkit-transition: all 0.5s linear;
-moz-transition: all 0.5s linear;
-ms-transition: all 0.5s linear;
-o-transition: all 0.5s linear;
transition: all 0.5s linear;
}
a.fadeBlack:hover img {
opacity: 0.6;
background-color: #000;
}

这是我的JSFiddle

1 个答案:

答案 0 :(得分:1)

使用left: 50%top: 50%transform: translate(-50%, -50%)垂直和水平居中.picDisc

<强> Updated Fiddle

.photoGallery img {
  background: #181818 no-repeat;
  border-radius: 10px;
}
.blackBG {
  position: relative;
  display: inline-block;
  border-radius: 10px;
}
.picDisc {
  position: absolute;
  top: 50%;
  left: 50%;
  -webkit-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
  z-index: 1;
}
a.fadeBlack img {
  display: block;
  -webkit-transition: all 0.5s linear;
  -ms-transition: all 0.5s linear;
  transition: all 0.5s linear;
}
a.fadeBlack:hover img {
  opacity: 0.6;
  background-color: #000;
}
<a href="#" class="fadeBlack">
  <span class="blackBG">
        <p class="picDisc">TEST</p>
        <img src="http://www.mountainguides.com/photos/everest-south/c2_2011b.jpg" width="100%" height="100%" />
    </span>
</a>