Div Align With CSS

When playing with custom web designs, or off the shelf templates, the most common CSS work involves changing the margin, padding, color and background of HTML elements. I usually also usually align elements either to the left, right, or center using CSS.

To get started with code samples, to center a div in the middle of a container div you can use the following CSS:

.center {
  margin-left: auto;
  margin-right: auto;
}

If you want to align a div to the right and another div opposite to the first on the left you can use the following CSS classes.

.right {
  float: right;
}
.left {
   float: left;
}

I have found that when I used both div that float both to the right and left that you have to follow that with an empty div that clears, or resets, the float CSS property. If I don’t clear the float property other elements such as a menu that is aligned to the right might not render correctly. Here is the CSS class to clear the float property, use it in a div the divs that have been aligned to the right, left, or both right and left.

.clear {
  clear: both;
}

Technorati Tags: , , , , , ,

HTML FieldSet Tag »
« SF Ruby Meetup
 
Related Posts
Recent Posts
 

2 Comments so far

  1. Francisco Hernandez on January 14th, 2007

    You an avoid the evils of structural markup by using a technique as described here: http://www.positioniseverything.net/easyclearing.html

  2. Jeyaseelan M A J on July 10th, 2007

    Very useful. I was actually amazed and perplexed that there was no div-align in CSS. I am glad there is at least a work-around

Leave a reply