div中的水平中心动态图像,绝对位置

时间:2022-11-18 17:03:33

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

2 个解决方案

#1


60  

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

如果你想要它是绝对位置,那就这样:

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.

父母需要有相对位置,或者它将被定位在身体上。你不需要宽度,我只是包括宽度,因为我的图像是如此之大。

#2


0  

left = center position - half the width of the image

left = center position - 图像宽度的一半

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

#1


60  

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

如果你想要它是绝对位置,那就这样:

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.

父母需要有相对位置,或者它将被定位在身体上。你不需要宽度,我只是包括宽度,因为我的图像是如此之大。

#2


0  

left = center position - half the width of the image

left = center position - 图像宽度的一半

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