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: css, html, webdesign, clear, float, div, cs class
Related posts:
5 Comments
You an avoid the evils of structural markup by using a technique as described here: http://www.positioniseverything.net/easyclearing.html
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
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. :)
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
Thanks for this post. I am having a lot of trouble with ie7 trying to align the div elements.