垂直对齐图像顶部的中间和居中文本

时间:2017-01-19 10:12:21

标签: html css

我正在尝试使用垂直对齐的中间和文本对齐中心将文本放在图像上。但是他们似乎都没有工作。

我的HTML是

<div class="hero-image">
  <img src="https://s23.postimg.org/ahcg75tsb/hero.png" alt="">
  <a href=""><h2>Some Sample text</h2></a>
</div>

演示 - https://jsfiddle.net/squidraj/zkno1sc2/

是不是因为我没有在父div中指定图像的宽度?

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:2)

您可以display: flex.hero-image结合使用align-items: center;

.hero-image {
  display: flex;
  position: relative;
  align-items: center;
}
.hero-image img{
  width: 100%;
}

.hero-image h2 {
  background: #ff2bff none repeat scroll 0 0;
  color: #fff;
  text-align: center;
  width: 200px;
  margin: 0px auto;
  position: absolute;
  left: 0;
  right: 0;
}
<div class="hero-image">
  <img src="https://s23.postimg.org/ahcg75tsb/hero.png" alt="">
  <a href=""><h2>Some Sample text</h2></a>
</div>

答案 1 :(得分:0)

制作&#34; top&#34;填充,请参阅代码:

&#13;
&#13;
.hero-image {
  display: block;
  position: relative;
}

.hero-image a {
  background: #ff2bff none repeat scroll 0 0;
  color: #fff;
  left: 0;
  position: absolute;
  right: 0;
  text-align: center;
  top: 45%;
  width: 200px;
  bottom: 0;
  vertical-align: middle;
  text-align: center;
  margin: 0px auto;
  height: 50px
}
&#13;
<div class="hero-image">
  <img src="https://s23.postimg.org/ahcg75tsb/hero.png" alt="">
  <a href=""><h2>Some Sample text</h2></a>
</div>
&#13;
&#13;
&#13;

相关问题