且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

CSS:如何在图像上垂直和水平居中放置文本

更新时间:2022-03-31 09:44:44

只使用绝对位置并翻译。会完美居中(水平和垂直)

Just use position absolute and translate. Will be perfect centered (horizontally and vertically)

.img_container {
  position: relative;
}
.img_container img {
  width: 100%;
  height: auto;
}
.img_container h2 {
  color: white;
  text-shadow: 1px 1px 1px black;
  position: absolute;
  top: 50%;
  left:  50%;
  -webkit-transform: translate(-50%, -50%); /* iOS */
  transform: translate(-50%, -50%);
}

<div class="img_container">
  <img class="cover-image" src="http://lorempixel.com/400/200/sports/" alt="omg" />
  <h2> bla bla bla </h2>
</div>