简体   繁体   中英

Center an image on top of a div

I have a div with a bunch of stuff in it and what I want to do is place an image, centered, on top of it. My basic layout looks something like this:

<div>
    <img style="display:block; position: absolute; top:50%; left:50%; margin-top:-33px; margin-left:-33px;" src="Images/ajax-loader_001.gif" />
    <!-- a bunch of tables and stuff that doesn't have a conveniently fixed size  -->
</div>

The above will center the image in the screen (the image is 66px x 66px BTW), but I want it centered relative to the parent div and "floating" above it. Is there a purely css way of doing this? Needs to work in IE8 and recent Firefox versions.

Edit: just to clarify - I'm looking to center both horizontally and vertically and on top of the parent.

只需要把它放在你的父div上:

position: relative;

You can use:

<div>
    <img style="display:block; position: relative; margin:auto" src="Images/ajax-loader_001.gif" />
    <!-- a bunch of tables and stuff that doesn't have a conveniently fixed size  -->
</div>

This will work for sure.

You should remove all the absolute positioning stuff and instead do this img { display: block; margin: 0 auto; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM