Centering things with CSS

on

There are still many people out there who have difficulties with getting things centered when doing webdesign. In this post I’ll explain some core techniques to achieve this.

Centering text

The most basic way of getting text centered is the text-align css property. Examine following rule:

p#title { text-align: center; }

this will get the text paragraph with id “title” centered relative to its parent element. By using text-align: right you can easily align text to the right of the parent element.

Center divs horizontaly #1

The basic way to center any element (you could even do this with text) is the use the following css rule.

div#header { width:400px; height: 100px; margin: 0 auto; }

The above line sets a margin of 0 for the top and bottom ( = nothing) and auto-adjusts the margin for the left and right property of the specified div. The browser basically pushes the left/right side of the div until there’s no room left and the div is positioned in the middle of the screen with equal left/right margins. (play with various px values for auto and you’ll see what I mean)

The above is shorthand for:

div#header { width: 400px; height:100px; margin-left: auto; margin-right: auto; }

Centering divs horizontaly #2

You can also use a second technique when using absolute or relative positions. Game developers might be more familiar with this, though it’s certainly a plus when you master this centering technique.

The following rule basically tells the div to put its  top-left point in the center of the screen, then we only need to offset it by half the width of the div, then the div will look like it’s centered.

div #header { width:400px; height:100px; position: relative; left: 50%; margin-left:-200px; }

Centering divs vertically

Unfortunately “margin: auto 0” doesn’t work for vertical positioning, but the above code snippet works with a little modification. This time we need to position it with the top-left point in the vertical center of the screen and move it up with half of the height.

div #header { width:400px; height:100px; position: relative; top: 50%; margin-top:-100px; }

Hopefully you learned something new here. The above code snippets apply to all selectors, but I advise you to always wrap a div with an id or class to each object you create in HTML (whether it’s an image, iframe, form, …) Thinking alongside the CSS box model is the way to success.

Nick

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s