Forum Moderators: not2easy

Message Too Old, No Replies

How do i center images in css

center images css

         

Mr_T

1:18 pm on Sep 5, 2008 (gmt 0)

10+ Year Member



Hi all, i'm having trouble centering images with css.

I've read previous posts and just cant seem to get it right.

Below is the html i'm using and the css from the style sheet.

Have i done something stupid or missed something simple.

Any help much appreciated

Thanks in advance

<div class="htmlcss">
<a href="http://validator.w3.org/check?uri=referer"><img src="/images/valid_html.png" alt="Valid HTML 4.01 Strict" height="31" width="88"></a>
<a href="http://jigsaw.w3.org/css-validator/check/referer"><img src="http:/images/valid_css.gif" alt="Valid CSS!" height="31" width="88"></a>
</div>

.htmlcss
{
display: block;
margin-left: auto;
margin-right: auto
}

tangor

2:01 pm on Sep 5, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I've done it one way for so long I've never investigated another method:

<div align="center"><img src="whatever.png"></div>

Just seems cleaner. I'm sure there are many ways to do this.

rocknbil

3:46 pm on Sep 5, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



If you were to put a border on the div,

.htmlcss {
border: 1px solid #000000;
margin: auto;
}

You would probably see it is the full with of the parent, rendering the margins useless. Put a width on it:

.htmlcss {
border: 1px solid #000000;
width: 176px;
margin: auto;
}

(Then remove the border.) You might have to play with the width a little, depending on how much padding or margin is taken up by the images. If necessary, add text-align:center to the selector.

Mr_T

4:29 pm on Sep 5, 2008 (gmt 0)

10+ Year Member



Thank you both very much for the replies, much appreciated.

Now i can carry on with the rest of the site

swa66

10:52 pm on Sep 5, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Actually the width on the div only does part of it, it would need to fit tightly around the images to have a pixel perfect result.

These images are inline content, so you can use "text-align:center" on the parent (your htmlcss div) without having to guess an appropriate width. Much easier, much neater.

Mr_T

9:05 am on Sep 12, 2008 (gmt 0)

10+ Year Member



Thansk for that, i'll give it a try.

Sorry for the delay in thanking you, i've been away

sgietz

1:43 pm on Sep 12, 2008 (gmt 0)

10+ Year Member



Also, if you set all your images to display:block, you won't be able to use text-align:center unless you override that for individual images. As far as I'm concerned, text-align:center on an inline image is the most elegant way to center it.