Andre asks the CSS Guy how to center an image in a div
Andre writes:
how do you center images inside a div with css?
Andre, here's one way. If your html looks like this:
<div>
<img src="elephant_ball.jpg" alt="" />
</div>
Apply display:block; to the image, and also make sure it's left and right margins are set to "auto", like so:
<style type="text/css">
div img {
display:block;
margin:auto;
}
</style>
That should do it. View the example.
I hope you didn't mean "vertical" centering...
...because right now, there's no elegant and easy way to do it that's acceptable to all browsers. Below are some possible options to look into - pick your poison.
Comments (7)
paketep said:
Being images inline elements, isn't a simple "text-align: center" in the css enough to center them?
# March 7, 2007 6:14 PM
CSS Guy said:
@paketep:
Applying "text-align:center;" just to the image does not work.
If "text-align:center;" were applied to the div, then the image, along with all the other elements inside the div, would be aligned to the center. That's another very valid way to achieve the effect.
The method I proposed would center only the img, not other elements, within the div.
# March 7, 2007 10:05 PM
paketep said:
Ahhh, ok, thanks for clearing that.
Just curiosity, I also prefer to use the margin: auto way ;)
# March 8, 2007 12:34 PM
ia said:
This doesn't work in IE, right? :)
# March 13, 2007 4:13 PM
designedsomuch said:
@ia: why, works in IE pretty fine
# January 31, 2008 5:44 AM
Luis said:
if it looks like this
then you can add the tag around it.
# February 24, 2008 4:25 AM
Ben Clapton said:
Would it not be easier to create a class for your img tags. You can then create 3 different classes - one for left, right and centred, with the following code:
img.left {
float:left;
}
img.right {
float:right;
}
img.centre {
display:block;
margin-left:auto;
margin-right:auto;
}
Then, when you want to centre an image, you would use:
<img class="centre" src="whatever.jpg" />
That centres the image without the need for an extra div, and also allows you to set the padding so you can either have the text hugging it or a little bit off.
# July 22, 2008 10:13 AM