css 在父div中居中图像元素

xmakbtuz  于 2023-06-25  发布在  其他
关注(0)|答案(6)|浏览(77)

如何在父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; }
dw1jzc5e

dw1jzc5e1#

text-align: center; CSS声明添加到父.box,而不是子.box img

.box {
    height: 100%;
    width: 450px;
    border: 2px solid red;
    background: green;
    overflow: hidden;
    text-align: center;  /* align center all inline elements */
}

这里是**Fiddle**。

更新

图像下面好像还有一个5px的缺口,属于行高预留字符。要从像<img>这样的内联元素中删除它,可以使用vertical-align: bottom

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

JSFiddle Demo #2

qoefvg9y

qoefvg9y2#

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

就是这样!

ecbunoof

ecbunoof3#

如果有人在这里寻找解决方案,这里有一个使用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;
}
gkn4icbw

gkn4icbw4#

如果您的父div具有宽度,则尝试将图像margin属性指定为margin:0 auto,以便图像将按照父div居中

iqih9akk

iqih9akk5#

如果以百分比表示宽度,则可以使用边距居中:

.box img {
    width: 80%;
    margin-left: 10%;
    margin-right: 10%;
}
ycggw6v2

ycggw6v26#

我会把它添加到.box img中。

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

你可能需要对每个图像进行调整,或者因为尺寸的关系而不需要调整。

相关问题