15

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.

Here is my 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:

#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:

bottom-centered img - js.fiddle

2 Answers 2

68

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.

5
  • Thank you for your help. That was all I needed.
    – Ben Cohn
    Jul 15, 2013 at 12:32
  • This was the right solution. Thanks I had no idea about left:0 and right: 0 and margin-left: auto and margin-right: auto !!! Apr 18, 2014 at 9:25
  • 1
    I know it's 2 years too late. But this answer should be accepted @Ben Cohn
    – HCN
    Jul 27, 2015 at 8:56
  • I'm not sure if this was an intentional omission or accidental, but I needed to add top: 0; as well in order for the image to be centered both vertically and horizontally. Mar 21, 2018 at 16:36
  • I didn't include it, because the question was about horizontal centering only. Mar 21, 2018 at 16:42
0

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*/
}

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.