当前位置: 动力学知识库 > 问答 > 编程问答 >

html - How to center an image that contains absolute elements inside?

问题描述:

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:

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;}

网友答案:

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;
}
网友答案:

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

The solution is from this other post http://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;}
网友答案:

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. :)

分享给朋友:
您可能感兴趣的文章:
随机阅读: