2017-02-07 63 views
0

我有以下代码中心文字立式元素改变高度和宽度

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; 
} 

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

+0

可能重复的[如何将元素水平和垂直居中?](http://stackoverflow.com/questions/19461521/how-to-center-an-element-horizo​​ntally-and-vertically) – chazsolo

回答

2

我发现计算器这一招还有,我会当我再次找到它添加一个链接:

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

做是因为translateY需要的元素的高度,并top使用的高度周围的元素。

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

0

你应该尝试使用flexbox,如果可能使你的HTML的一些变化。

在我看来,以使这项工作我会用:

HTML

<a href="#" class="col-inner"> 
    <div class="content"> 
    <h3>Hello World</h3> 
    <p>Lorem Ipsum Dolor Sit Amet</p> 
    </div> 
</a> 

CSS

.col-inner{ 
    max-width: 100%; 
    min-height: 150px; 
    position: relative; 
    background-image: url('http://placehold.it/450x450'); 
    background-repeat: no-repeat; 
    background-size: cover; 
    background-position: 50% 50%; 
    display: flex; 
    justify-content:center; 
    align-items:center; 
} 
.content{ 
    color: #ff0000; 
} 

我刚添加的图像作为background-image的标签,作为行为一个容器,并且使用display: flex; justify-content:center; align-items:center以水平方式&将文本和容器内的所有元素垂直居中。

你可以调整height.col-inner,看看不管这个班级有多高,它总是居中。

我已经设置了codepen发挥它:code

请记住,如果你想使用flexbox你应该前缀代码。使用此网站caniuse查看应添加到flexbox和相关属性的前缀。