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: , , , , , ,

Related posts:

  1. The 1Kb CSS Grid
  2. CSS Hackary
  3. Rounded Corners With Rico
  4. Import Script, Import CSS, Import PHP
  5. Unobtrusive JavaScript with Prototype and Behavior

This entry was posted in CSS, HTML/XML, TechKnow. Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

5 Comments

  1. Francisco Hernandez
    Posted January 14, 2007 at 11:51 pm | Permalink

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

  2. Posted July 10, 2007 at 11:51 pm | Permalink

    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

  3. Posted June 11, 2009 at 2:17 pm | Permalink

    Good stuff. Something to keep in mind is that IE doesn’t like the “margin: 0 auto” trick to center a div. In addition to that, you can add “text-align: center” to a wrapping div. Just make sure to do “text-align: left” on your centered div if you don’t want your text centered. :)

  4. Posted June 17, 2010 at 5:16 pm | Permalink

    We’re in the process of designing our Web site for the upcoming release of our product and kept fumbling around with aligning DIVs — this post on alignment with CSS really helped. Thanks for sharing!

    –Kevin

  5. Posted June 6, 2011 at 11:10 pm | Permalink

    Thanks for this post. I am having a lot of trouble with ie7 trying to align the div elements.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*