如何在父div中设置图像元素的中心?我想这样做,使中间的形象始终是在中心,他的父母。此外,我希望图像总是有100%的高度(注:我不想拉伸图像宽度)。
请参阅此处的示例:http://jsfiddle.net/Ex5ax/5/
<div class="box">
<img src='featured.jpg' />
</div>
CSS:
.box { height: 100%; width: 450px; border: 2px solid red; background: green; overflow: hidden; }
.box img { height: 100%; width: auto; text-align: center; }
6条答案
按热度按时间dw1jzc5e1#
将
text-align: center;
CSS声明添加到父.box
,而不是子.box img
。这里是**Fiddle**。
更新
图像下面好像还有一个
5px
的缺口,属于行高预留字符。要从像<img>
这样的内联元素中删除它,可以使用vertical-align: bottom
:JSFiddle Demo #2
qoefvg9y2#
你需要将
text-align: center;
从图片的CSS移动到其父div的CSS,这样你的CSS看起来像这样:就是这样!
ecbunoof3#
如果有人在这里寻找解决方案,这里有一个使用
display: flex
的解决方案。gkn4icbw4#
如果您的父div具有宽度,则尝试将图像margin属性指定为
margin:0 auto
,以便图像将按照父div居中iqih9akk5#
如果以百分比表示宽度,则可以使用边距居中:
ycggw6v26#
我会把它添加到.box img中。
你可能需要对每个图像进行调整,或者因为尺寸的关系而不需要调整。