[英]How to center an image horizontally and align it to the bottom of the container?
如何將圖像水平居中並同時對齊容器底部?
我已經能夠通過自我水平居中。 我也能夠通過它自己對齊容器的底部。 但我無法同時做到這兩點。
這是我有的:
.image_block {
width: 175px;
height: 175px;
position: relative;
margin: 0 auto;
}
.image_block a img {
position: absolute;
bottom: 0;
}
<div class="image_block">
<a href="..."><img src="..." border="0"></a>
</div>
該代碼將圖像與div的底部對齊。 我需要添加/更改什么才能使圖像在div內水平居中? 圖像尺寸在手前是未知的,但是它將是175x175或更小。
.image_block {
width: 175px;
height: 175px;
position: relative;
}
.image_block a {
width: 100%;
text-align: center;
position: absolute;
bottom: 0px;
}
.image_block img {
/* nothing specific */
}
解釋 :絕對定位的元素將相對於具有非靜態定位的最近父元素。 我假設您對.image_block
顯示方式感到滿意,因此我們可以將相對定位留在那里。
因此, <a>
元素將相對於.image_block
,這將給我們底部對齊。 然后,我們text-align: center
將<a>
元素text-align: center
,並給它一個100%的寬度,使它的大小為.image_block
。
<a>
的<img>
將適當地居中。
這也有效(從這個問題中得到了暗示)
.image_block {
height: 175px;
width:175px;
position:relative;
}
.image_block a img{
margin:auto; /* Required */
position:absolute; /* Required */
bottom:0; /* Aligns at the bottom */
left:0;right:0; /* Aligns horizontal center */
max-height:100%; /* images bigger than 175 px */
max-width:100%; /* will be shrinked to size */
}
不會
margin-left:auto;
margin-right:auto;
添加到.image_block
一個img做的伎倆?
請注意,這在IE6中不起作用(可能7不確定)
你必須在.image_block
上做容器Div
text-align:center;
position:relative;
也可能是一個問題。
這很棘手; 它失敗的原因是你無法通過邊距或文本對齊定位,而絕對定位。
如果圖像在div中是單獨的,那么我推薦這樣的東西:
.image_block {
width: 175px;
height: 175px;
line-height: 175px;
text-align: center;
vertical-align: bottom;
}
您可能需要在圖像上粘貼vertical-align
調用; 不測試就不太確定。 然而,使用vertical-align
和line-height
會讓你感覺好多了,而不是試圖搞清楚絕對定位。
刪除position: relative;
線。 我不確定為什么,但它為我修復了它。
你有沒有嘗試過:
.image_block{
text-align: center;
vertical-align: bottom;
}
#header2
{
display: table-cell;
vertical-align: bottom;
background-color:Red;
}
<div style="text-align:center; height:300px; width:50%;" id="header2">
<div class="right" id="header-content2">
<p>this is a test</p>
</div>
</div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.