Thursday, November 04, 2010

How to Center an Image with CSS

Before I throw away the decorations, I want to show you a CSS technique for centering an image like the flags I had hanging from the top of the browser window for the elections. I tried it two different ways.

First time I repeated the image across the top which only takes a height and background statement that repeats horizontally. You have to specify height for divs that do not have content. A background image will collapse without content and you will see nothing on screen.

#special_events {
background: url(images/flagcascades2.jpg) 0 0 repeat-x;
height: 85px;
}
<div id='special_events'/>

background with repeat-x

This looked fine and a lot of people will be pleased with it but it was too busy for my taste. I decided to place a single image over the main content that moved with the middle column. In order to make this work correctly, you have to do two things.

When the browser window resizes in order to flow the flag with the main content, we have to auto margin the left and right margins. But for that to work, the browser needs to know the width of your element. Then based on that width, it will center the div with the margin: 0 auto; statement. If you don't give the div an explicit width, it'll take the full width of the browser because it's a block element and block elements expand horizontally all the way across their containing block. Doing "margin: 0 auto;" won't have any effect in that situation since the div goes all the way across.

To rewrite special_events, we will give the div a width equal to its background image and take the horizontal repeat out of the background rule.

#special_events {
background: url(images/flagcascades2.jpg) 0 0 no-repeat;
height: 85px;

/* to center it as the browser window resizes */
width: 872px;
margin: 0 auto; }
}
<div id='special_events'/>

background with no-repeat

Post a Comment