CSS div中具有绝对位置的水平居中动态图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17624097/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 23:30:08  来源:igfitidea点击:

Horizontal center dynamic image in div with absolute position

cssimagedynamiccenter

提问by Ben Cohn

I have looked all over the web for this answer but it seems to me that in order to horizontally center an image in div with absolute position, I need to know the dimensions of the image, but it's dynamic.

我已经在网络上寻找了这个答案,但在我看来,为了将图像水平居中放置在具有绝对位置的 div 中,我需要知道图像的尺寸,但它是动态的。

Here is my html:

这是我的 html:

<header>
<div id="elogo">
    <img src="http://www.ftiweb.com/images/eStore/eStore_wht50.png">
</div>
<div id="nav">TOUR | MENU</div>
</header>
<div id="content">
<img class="ipad" src="http://ftiweb.com/images/eStore/Ipad_hand.png">
</div>
<footer>
<div id="foot">&#169; FTIeStore 2013 &bull; Privacy Policy</div>
</footer>

and here is the .css I'm using:

这是我正在使用的 .css:

#content {
width: 70%;
height: 80%;
border: 1px solid red;
position: absolute;
bottom: 0px;
left: 50%;
margin-left: -35%;
display: table-cell;

img.ipad {
max-width: 100%;
max-height: 100%;
position: absolute;
bottom: 0px;
display: block;
}

The goal is just to have the image stay at the bottom/center of the page and re-size to fit the browser window. If I'm over-complicating this, please feel free to suggest an alternative.

目标只是让图像停留在页面的底部/中心并重新调整大小以适合浏览器窗口。如果我过于复杂,请随时提出替代方案。

Here is a link to a js.fiddle:

这是一个 js.fiddle 的链接:

bottom-centered img - js.fiddle

底部居中的 img - js.fiddle

回答by user1721135

If you want it to be absolute position do it like this:

如果您希望它是绝对位置,请这样做:

http://jsbin.com/aveped/1/edit

http://jsbin.com/aveped/1/edit

img {
  width:20%;
  display:block;
  position:absolute;
  left:0;
  right:0;
  bottom:0;
  margin:auto;
}

The parent needs to have position relative, or it will be positioned against the body. You dont need width for this, I just included width because my image is so big.

父级需要有相对位置,否则它将靠在身体上。你不需要宽度,我只是包括宽度,因为我的图像太大了。

回答by Grant

left = center position - half the width of the image

左 = 中心位置 - 图像宽度的一半

img {
   position: absolute;
   bottom: 0;
   left: 50%; /*half the container width*/
   margin-left: -250px; /*half the width of the image*/
}