在改变高度和宽度的元素中垂直居中文本 [英] Center Text Vertical In Element That changes Height and Width

查看:83
本文介绍了在改变高度和宽度的元素中垂直居中文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码

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

这篇关于在改变高度和宽度的元素中垂直居中文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆