Html 父 div 中的中心图像元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18428997/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Center image element in parent div
提问by Caspert
How I can set center an image element inside a parent div? I would like to do this so that the middle of the image is always in the center of his parent. Also I want the image to always have 100% height (note: I don't want to stretch the image width).
如何在父 div 中设置图像元素的中心?我想这样做,以便图像的中间始终位于他父母的中心。此外,我希望图像始终具有 100% 的高度(注意:我不想拉伸图像宽度)。
See here for an example: http://jsfiddle.net/Ex5ax/5/
见这里的例子:http: //jsfiddle.net/Ex5ax/5/
<div class="box">
<img src='featured.jpg' />
</div>
CSS:
CSS:
.box { height: 100%; width: 450px; border: 2px solid red; background: green; overflow: hidden; }
.box img { height: 100%; width: auto; text-align: center; }
回答by Hashem Qolami
Add text-align: center;
CSS declaration to the parent .box
instead of the children .box img
.
将text-align: center;
CSS 声明添加到 parent.box
而不是 children .box img
。
.box {
height: 100%;
width: 450px;
border: 2px solid red;
background: green;
overflow: hidden;
text-align: center; /* align center all inline elements */
}
Here is the Fiddle.
这是小提琴。
Update
更新
It seems there's also a 5px
gap under the image, It belongs to the line height reserved characters. To remove that from inline elements like <img>
you can use vertical-align: bottom
:
5px
图片下方好像也有一个缺口,属于行高保留字符。要从内联元素中删除它,<img>
您可以使用vertical-align: bottom
:
.box img {
height: 100%;
width: auto;
vertical-align: bottom; /* <-- fix the vertical gap */
}
回答by Dhruv Kapoor
You'll need to move the text-align: center;
from the CSS for the image to the CSS for its parent div, so your CSS looks like this:
您需要将text-align: center;
图像的 CSS移动到其父 div 的 CSS,因此您的 CSS 如下所示:
.box {
height: 100%;
width: 450px;
border: 2px solid red;
background: green;
overflow: hidden;
text-align:center
}
.box img {
height: 100%;
width: auto;
}
And that's it!
就是这样!
回答by Ichigo Kurosaki
Try giving the image margin property as margin:0 auto
, if your parent div has width so the image will be centered as per parent
尝试将图像边距属性设置为margin:0 auto
,如果您的父 div 具有宽度,则图像将按父级居中
回答by Lewes
I would add this to .box img.
我会将此添加到 .box img。
.box img { margin-left: -25%; margin-top: -25%; }
You would probably need to ajust these per image, or maybe not due to the dimensions.
您可能需要调整每张图像的这些,或者可能不是由于尺寸。