Friday, October 17, 2008

[TIP] CSS: How to center an element

CSS can be strange at times. Most of CSS makes logical sense, but some CSS techniques defy any logic.

Where this got highlighted for me was trying to teach one of staff CSS. She often gets confused when I demand more advanced CSS. So I concluded that some CSS just needs to be remembered and cannot logically be figured out like one does in a computer program. Ah Well!

Here is one such example:

Centering an element in CSS.

The HTML:

<div id="main">
<!-- content goes here -->
</div>

The CSS:

body {
text-align: center; /* Center main in IE */
}
#main {
width: 768px; height: 768px;
margin: 0px auto -1px auto;
/* Center main in other browsers */
}

Firstly there is a difference between IE and other browsers. The IE one is kinda obvious but seems not to be standards compliant. The use of the margin property is interesting. In case you didn't pick up on it it is the "auto" value that does the centering.

Hope this helps someone.

No comments: