11

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).

See here for an example: 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; }
4

5 回答 5

12

Add text-align: center; CSS declaration to the parent .box instead of the 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:

.box img {
    height: 100%;
    width: auto;
    vertical-align: bottom; /* <-- fix the vertical gap */
}

JSFiddle Demo #2

于 2013-08-25T12:32:37.777 回答
3

您需要将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;
}

就是这样!

于 2013-08-25T12:45:16.767 回答
0

尝试将图像边距属性设置为margin:0 auto,如果您的父 div 具有宽度,则图像将根据父级居中

于 2013-08-25T12:46:22.607 回答
0

如果有人在这里寻找解决方案,这里有一个使用display: flex.

.box {
   display:flex;
   justify-content: center;
   align-items: center;
   background: green;
   border: 2px solid red;
   height: 100%;
   width: 450px;
   overflow: hidden;   
}
.box img {
  justify-content: center;
  align-items: center;
}
于 2021-06-29T06:00:50.333 回答
-1

我会将其添加到 .box img 中。

.box img { margin-left: -25%; margin-top: -25%; }

您可能需要调整每个图像的这些,或者可能不是由于尺寸。

于 2013-08-25T12:52:05.213 回答