如何在响应式图片上垂直居中文本?

6
我如何在浏览器窗口调整大小时使这些图像的标题文本移动?我的实现效果不佳,我需要一种方法来防止文本在窗口调整大小时滑动。 Codepen
<div class="row">
  <div class="col-md-6">
    <img src="http://placekitten.com/600/375" class="img-responsive" />
    <h2 class="homeImageLink">
      <span>Caption Text</span>
    </h2>
  </div>
  <div class="col-md-6">
    <img src="http://placekitten.com/600/375" class="img-responsive" />
    <h2 class="homeImageLink">
      <span>Caption Text</span>
    </h2>
  </div>
</div>

.homeImageLink {
   position: absolute; 
   top: 110px; 
   left: 0;
   text-align: center; 
   width: 100%; 
}

.homeImageLink span { 
    color: red;
    font-weight: 300;
    font-style: italic;
    text-transform: uppercase;
    letter-spacing: 15px;
    pointer-events: none;
}

你尝试过在span上使用 col-md-offset-4 col-md-4 类吗? - JanR
@JanR 没有,如果使用这种方法,如何处理垂直居中呢? - drewwyatt
算了,那行不通。我刚意识到你想做什么,但这对于叠加文本是行不通的。 - JanR
@JanR 唉,真遗憾。无论如何,感谢你的评论! - drewwyatt
发布了一个答案,不确定那是否是你想要的 :) 你是在谈论垂直对齐还是水平对齐?这个适用于水平对齐,其他答案展示了垂直对齐。 - JanR
2个回答

17

只需将一个类添加到父容器中,使其位置相对。

.img-container {
  position:relative;
}

然后将homeImageLink设为绝对定位,并在顶部设置大约45%的高度。

这将使其垂直居中。

.homeImageLink {
   position: absolute; 
   top: calc(50% - 24px); //24px is font size of H1 I assume 
   left: 0;
   text-align: center; 
   width: 100%; 
}

演示在这里:http://codepen.io/anon/pen/bJadE


为什么是 top:45% 而不是 50%? - Shawn Taylor
仅仅因为文本高度占用了一点高度。 - Rahul Patil
谢谢,你也可以像这里提到的那样添加 line-height。我正在尝试创建响应式的HTML电子邮件,并在图像上叠加文本。 - Shaiju T
1
不要使用 top: 45%,而是使用 top: calc(50% - [文字的字体大小])。 - ericgrosse
2
更好的方法是现在使用 top: 50%; transform: translateY(-50%);。不需要跟踪行高。 - myol
这是一个很好的答案。对于想要完美居中文本的完美主义者,请使用 top: calc(50% - ([总高度] / 2)),其中 [总高度] 是行高 + 上下内边距 + 上下外边距。 - Craig Brown

0

我想出了另一种解决方案,这里有一个可行的演示:

http://codepen.io/niente0/pen/jyzdRp

HTML:

<DIV class=wrapper>
     <DIV class=divimage></DIV>
     <DIV class=divtext>THIS IS A TEST</DIV>
</DIV>

CSS:

HTML,BODY {
  max-width:1200px;
}
.wrapper {
  position:relative;
  width:100%;
  max-width:1200px;
  height:100%;
  min-height:320px
}
.divimage {  position:absolute;
  top:0;
  left:0;
  width:100%;
  height:100%;
  background:url(https://thumbs.dreamstime.com/t/empty-red-banner-corners-ropes-textile-white-background-d-illustration-70434974.jpg);
  background-repeat:no-repeat;
  background-size:100% auto;
}
.divtext {
  position:absolute;
  top:0;
  left:0;
  width:100%;
  padding-top:13.5%;  
  text-align:center;
  font-weight:bold;
  font-size:5vw;
  color:white;
  font-family:arial;
}
@media (min-width: 1200px) {
  .divtext{
    font-size:60px;
  }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接