0

How to center an image that contains absolute elements inside ?

I've manage to position absolute elements in the image, but now i want to center the image inside de red container... how?

For example:

enter image description here

HTML

<div id="image">
    <div id="the-image">
        <img src="..." width="..." height="..." alt="">
        <a href="..."><img src="" alt=""></a>
    </div>
</div>

CSS

#image {background-color: red; float: left; width: 660px;}

#the-image {display: inline-block; position: relative;}
#the-image img {}
#the-image a {position: absolute; bottom: 10px; right: 10px;}
Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
Marco
  • 2,687
  • 7
  • 45
  • 61

3 Answers3

1

You could do this

#the-image {
    text-align: center;
    display: block;
}

#the-image img {
    display: inline-block;
}

or this

#the-image img {
    display: block;
    margin: 0 auto;
}

For this to work, you'd need to make sure that your images have a width attribute set.


EDIT :

http://jsfiddle.net/uLX8g/3/

#the-image {
 display: block; /* changed from inline-block to block */
}

#the-image img { 
    display: block; 
    margin: 0 auto;
}
CRABOLO
  • 8,605
  • 39
  • 41
  • 68
0

ok, after a couple of hours, i've found the solution... how could i have missed it!

The solution is from this other post https://stackoverflow.com/a/4980600/888139

it says: If you have a div with text-align:center;, then any text inside it will be centered with respect to the width of that container element. inline-block elements are treated as text for this purpose, so they will also be centered.

so, i just needed to make the div with the id image text-align center... and that's all.

<div id="image">
    <div id="the-image">
        <img src="..." width="..." height="..." alt="">
        <a href="..."><img src="" alt=""></a>
    </div>
</div>



#image {background-color: red; float: left; width: 660px; text-align: center}

#the-image {display: inline-block; position: relative;}
#the-image img {}
#the-image a {position: absolute; bottom: 10px; right: 10px;}
Community
  • 1
  • 1
Marco
  • 2,687
  • 7
  • 45
  • 61
-2

I don't want to make it complicated or whatever. But try this, see if it works.

<div id="image">
   <center>
      <div id="the-image">
           <img src="image.jpg" width="..." height="..." alt="">
            <a href="..."/><img src="" alt=""></a>
         </div>
     </center>
 </div>

This is just in case you need to put everything on centered. :)

user3335903
  • 1,475
  • 4
  • 14
  • 13