Friday, October 17, 2008

CSS Tips and Tricks

Every time I get back into CSS I forget some of the basic rules about inline and block level elements, positioning and box models. I'm not a fan of browser hacks, so you won't find any of those here.

Inline Elements

  • Can have width, padding-left, padding-right, margin-left and margin-right applied. However height, padding-top, padding-bottom, margin-top and margin-bottom are not applied.
  • To set the height you can use the line-height property.

Vertically Centered Text

  • An easy way center text vertically within an element is to use the line-height property. If the line-height is greater than the font size, the extra space is distributed evenly above and below the text.

Horzontally Centered Elements

  • Set a width and margin: 0 auto; on an element to have it horizontally centered.

Clearing Floats

  • Clearing floats with clear: left; clear: right; or clear: both; will clear all floats that precede the element in the document model. So use floats wisely because you will probably end up clearing floats on other parts of the page which you did not intent to clear.

Absolute vs Relative Positioned Elements

  • A relatively positioned element's margins will collapse (the margin will be the maximum of the two adjacent element's margins). However an absolutely positioned element will start a new block formatting context and its margins will not collapse with adjoining elements.
  • An absolutely positioned element is taken out of the document flow and positioned relative to the first positioned (rel or abs) ancestor.

100% Height Divs

  • Assigning height: 100% to a div will have no effect without a height defined on the parent.

No comments: