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;
}

6 Responses to “Div Align With CSS”

Leave a Reply