CSS has several properties that can be used to align elements on web pages.
See tutorial on CSS Text to learn more about text formatting.
Center Alignment Using the margin Property
Center alignment of a block-level element is one of the most important implications of the CSS
margin property. For example, the
<div> container can be aligned horizontally center by setting the left and right margins to
margin: 0 auto;
The style rules in the above example center align the
<div> element horizontally.
auto for the
margin property will not work in Internet Explorer 8 and earlier versions, unless a
<!DOCTYPE> is specified.
Aligning Elements Using the position Property
position in conjunction with the
bottom property can be used to align elements with respect to the document's viewport or containing parent element.
To learn more about positioning elements, see the tutorial on CSS positioning.
Left and Right Alignment Using the float Property
float CSS property can be used to align an element to the left or right of its containing block in such a way that other content may flow along its side.
Hence, if an element is floated to the left, content will flow along its right side. Conversely, if the element is floated to the right, content will flow along its left side.
One of the most confusing things about working with the float-based layouts is the collapsing parent. The parent element doesn't stretch up automatically to accommodate the floated elements. Though, this isn't always obvious if the parent doesn't contain any visually noticeable background or borders, but it is important to be aware of and must dealt with to prevent strange layout and cross-browser problem. See the illustration below:
You can see the
<div> element doesn't stretch up automatically to accommodate the floated images. This problem can be fixed by clearing the float after the floated elements in the container but before the closing tag of the container element.
Fixing the Collapsed Parent
There are several ways to fix the CSS collapsing parent issue. The following section will describe you these solutions along with the live examples.
Solution 1: Float the Container
The easiest way to fix this problem is to float the containing parent element.
Warning:This fix will only work in a limited number of circumstances, since floating the parent may produce unexpected results.
Solution 2: Using the Empty Div
This is an old fashioned way but is an easy solution and works across every browser.
/* html code snippet */
<div class="clearfix"> </div>
You could also do this by means of a
<br> tag. But this method is not recommended since it adds nonsemantic code to your markup.
Solution 3: Using the :after Pseudo-Element
.clearfix is applied to any container that has floating children.