[英]Center horizontally and vertically text in relative height div
我想在包含圖像的相對高度div中居中放置文本。 我使用絕對位置,但是當我的文字在兩行上時,文字沒有居中。 我已經嘗試過使用表格,但是由於img
它不起作用。
HTML:
<div id="hubs">
<h3>Nos Hubs</h3>
<hr>
<a class="thumbnail vignette-hub" href="http://kkw.fr">
<img style="opacity: 0.6;filter: alpha(opacity=60);" alt="Aéroport de Nantes" src="http://kkw.fr/uploads/upload-center/nantes-vue-aerienne091501270208.png" width="100%" />
<p class="txt-hub-image">
Hub de</br>Nantes
</p>
</a>
</div>
CSS:
.txt-hub-image {
z-index: 100;
position: absolute;
left: 0px;
top: 50%;
width: 100%;
height: 100%;
text-align: center;
text-decoration: none;
color: white;
font-weight: bold;
font-size: 16px;
}
.vignette-hub {
position: relative;
width: 25%;
min-width: 135px;
}
.thumbnail {
display: block;
padding: 4px;
margin-bottom: 20px;
line-height: 1.42857143;
background-color: #fff;
border: 1px solid #ddd;
border-radius: 4px;
-webkit-transition: border .2s ease-in-out;
-o-transition: border .2s ease-in-out;
transition: border .2s ease-in-out;
}
.thumbnail > img,
.thumbnail a > img {
margin-right: auto;
margin-left: auto;
}
a.thumbnail:hover,
a.thumbnail:focus,
a.thumbnail.active {
border-color: #337ab7;
}
.thumbnail .caption {
padding: 9px;
color: #333;
}
你有什么想法 ?
您需要對代碼段進行一些更改,以使其自動適用於所有尺寸:
p
標簽默認情況下具有margin-top
。 如果您不重置它,那么將其絕對定位在50%會變成50%+ margin-top
。 這需要重置。 top: 50%
,框將定位在容器高度的50%處,並且從該位置開始不斷添加文本。 因此,要使文本塊的中心與父塊的中心匹配,您必須將帶有文本的框平移其自身大小的50%。 這可以通過添加transform: translateY(-50%)
來完成transform: translateY(-50%)
。 height: 100%
p
標簽上的height: 100%
,可以將其刪除。 注意:使用transform
方法進行定位需要CSS3支持,但是我認為這應該不是問題,因為您已經在使用transition
。 如果要支持不兼容CSS3的瀏覽器,請查看此處提到的其他方法。 我添加了一個不同的答案,只是為了解釋我上面提到的前兩點。
.txt-hub-image { z-index: 100; position: absolute; left: 0px; top: 50%; width: 100%; text-align: center; text-decoration: none; color: white; font-weight: bold; font-size: 16px; /* added to fix the vertical centering */ margin-top: 0px; transform: translateY(-50%); } .vignette-hub { position: relative; width: 25%; min-width: 135px; } .thumbnail { display: block; padding: 4px; margin-bottom: 20px; line-height: 1.42857143; background-color: #fff; border: 1px solid #ddd; border-radius: 4px; -webkit-transition: border .2s ease-in-out; -o-transition: border .2s ease-in-out; transition: border .2s ease-in-out; } .thumbnail > img, .thumbnail a > img { margin-right: auto; margin-left: auto; } a.thumbnail:hover, a.thumbnail:focus, a.thumbnail.active { border-color: #337ab7; } .thumbnail .caption { padding: 9px; color: #333; }
<div id="hubs"> <h3>Nos Hubs</h3> <hr> <a class="thumbnail vignette-hub" href="http://kkw.fr"> <img style="opacity: 0.6;filter: alpha(opacity=60);" alt="Aéroport de Nantes" src="http://kkw.fr/uploads/upload-center/nantes-vue-aerienne091501270208.png" width="100%" /> <p class="txt-hub-image"> Hub de</br>Nantes </p> </a> </div>
將.txt-hub-image類的最高值從50%更改為25%。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.