在改变高度和宽度的元素中垂直居中文本

问题描述:

我有以下代码

http ://codepen.io/anon/pen/EZeVXG

HTML

<a href="#" class="col-inner">
 <img src="http://placehold.it/450x450" />
 <div class="content">
   <h3>Hello World</h3>
   <p>Lorem Ipsum Dolor Sit Amet</p>
 </div>
</a>

CSS

img{
 max-width: 100%;
 height: auto;
}
.col-inner{
 position: relative;
 display: inline-block;
}
.content{
 position: absolute;
 width: 90%;
 height: 90%;
 top: 5%;
 left: 5%;
 background-color: rgba(0,0,0,.7);
 color: #FFF;
 text-align: center;
}

我尝试了一堆堆栈溢出技术,但似乎一切只有当你知道宽度和高度时才工作。这两个属性将随着您浏览器的弹性而改变。有没有什么办法让文本垂直居中?

I've tried a bunch of techniques found on Stack Overflow but everything seems to work only if you know the width and height. Both of those properties will change as you flex the browser. Is there any way to keep the text centered vertically the whole way?

我在stackoverflow上也找到了这个技巧,我会添加一个链接,只要我再次找到它:

I found this trick on stackoverflow as well, I will add a link as soon as i find it again:

height: auto; // (this is the default)
position: absolute;
top: 50%;
transform: translateY(-50%);

因为 translateY 的高度为元素和 top 使用周围元素的高度。

That works because translateY takes the height of the element, and top uses the height of the surrounding element.

http://codepen.io/anon/pen/zNJvgg