I have encountered a at many places, but I am not aware why is it done? Can someone brief me on this, why it is used in
The height of an element is determined by its child elements (unless it is explicitly set). E.g.:
+------A------+
|+-----------+|
|| B ||
|+-----------+|
|+-----------+|
|| C ||
|+-----------+|
+-------------+
The height of A is determined by where the lower border of its child C is.
Now, floating elements do not count towards the height of their parents, they're taken out of the regular flow:
+------A------+
+--+---------++
| B |
+---------+
+---------+
| C |
+---------+
The A element is collapsed to a minimal height, because its two children are floated.
Clearing elements are introduced to restore the correct height:
+------A------+
| +---------+|
| | B ||
| +---------+|
| +---------+|
| | C ||
| +---------+|
|+-----D-----+|
+-------------+
The D element is a zero-height element with the clear
attribute set. That causes it to fall below the floated elements (it clears them). That causes A to have a regular child element to calculate its height by. That's the most typical use case at least.
The often better solution to introducing extra HTML elements is to set A to overflow: hidden
though. That has the effect of forcing a height calculation, which has the same effect of growing the height to the desired size. This solution may or may not have other side effects though.