Fixing Floating Parent Divs

It is frustratingĀ  to float a child element only to find that every element appears to take the same positioning or find the child spilling beyond the borders of the parent. This brief article presents a modern solution to this issue using the display attribute in CSS.

Problem

At times when using the float attribute, elements placed in siblingsĀ  to a parent tag or even the siblings appear to inherit the floating properties of the target element. Elements may also appear to expand beyond the boundaries of a parent tag.

There are a few root causes of an element causing the parent’s siblings to appear to float including:

  • the zero height problem where an element is larger than its parent
  • the width of an ancestor is specified and violated by the child element

Solution

An older solution to the issue is to use the clear fix hack. However, with modern browsers, the solution is simpler:

.textedit-stylesheet-attr-div{
    display: flow-root;
}

Specifying flow-root causes the block format to be followed for the elements in the parent. This will maintain the float property of the children and cause the parent to ‘fit’ the child elements.