Contact Form    |   Email    |    Site Map
RSS

CSS: How does one float center?

When developing the login screen in Exam Professor we wanted to restrict its width to 500 pixels and have it "float" in the center of the layout. Sounds easy, right? I use Dreamweaver 8 which helps speed hand coding by offering hints as tags are typed and I notice:

float: left
float: right

but no float:center

Hmm....

The reason float: center doesn't exist in CSS is because you can assign the margin to an auto value, so both sides get the same amount.

For instance, if I have a <div id="login"> my CSS would look like this:

<style>
#login {
margin: 10px auto 0 auto;
width: 500px;}
</style>

The margin tag above reads 10px on top, auto margin on the right, 0px on the bottom, and auto margin on the left (think clockwise: top, right, bottom, left). The auto values for left and right margins center the element on the page.

Use this technique when you want to center elements on the page, but text-align:center when you want to center text within an element.