2017-02-07 133 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和相關屬性的前綴。