如何将图像水平居中并同时对齐容器底部?
我已经能够通过自我水平居中.我也能够通过它自己对齐容器的底部.但我无法同时做到这两点.
这是我有的:
.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>
Run Code Online (Sandbox Code Playgroud)
该代码将图像与div的底部对齐.我需要添加/更改什么才能使图像在div内水平居中?图像尺寸在手前是未知的,但是它将是175x175或更小.
Owe*_*wen 64
.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 */
}
Run Code Online (Sandbox Code Playgroud)
解释:绝对定位的元素将相对于具有非静态定位的最近父元素.我假设你对你的.image_block显示器感到满意,所以我们可以在那里保留相对位置.
因此,<a>元素将相对于该元素定位.image_block,这将使我们进行底部对齐.那么,我们text-align: center的<a>元素,并给它一个100%的宽度,使它的大小.image_block.
所述<img>内<a>然后将适当地居中.
vdu*_*dua 19
这也有效(从这个问题中得到了暗示)
.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 */
}
Run Code Online (Sandbox Code Playgroud)