Pro HTML5 and CSS3 Design Patterns

(avery) #1
CHAPTER 7 ■ POSITIONING MODELS

Float and Clear


Problem You want to remove an element from the normal flow and display it on the left or right
side of its parent. You want it rendered as a block aligned to the inside of its parent’s
padding. You also want its top to align with the line from which it was extracted. You also
want to control when other floats and nonfloated content flows next to floats or is moved
below them on one or both sides.


Solution You can use float:left or float:right to remove an element from the normal flow and
place it on the left or right inner edge of its parent’s padding area. You can use float:none
to override another rule that floats an element. Floats exist in their own layer above the
backgrounds of block elements and next to inline content in the normal flow. A left float
indents content on its right side, and a right float indents content on its left. A float doesn’t
affect the position of block boxes—just their inline content. Floats affect the position of
other floats and may be stacked next to each other on the left or right. Floats also may
push down other floats and inline content. A float’s vertical and horizontal margins offset
it from its parent and from other floats. Floats don’t overlap other floats or content (unless
a float has a negative margin).
You can use clear:left to move a block or float below any floats on its left side. You can
use clear:right to move a block or float below any floats on its right side. You can use
clear:both to move a block or float below floats on its right or left.


Patterns SELECTOR { float:none; }
SELECTOR { float:left; }
SELECTOR { float:right; }
SELECTOR { clear:none; }
SELECTOR { clear:left; }
SELECTOR { clear:right; }
SELECTOR { clear:both; }


Location Any element can be floated. clear works on tables, blocks, and floats. clear has no effect
on inline, absolutely positioned, or fixed-position elements.


Tips When you need to predict the vertical location of a float, it’s best to float a block element. A
browser places the top of a floated block exactly where it would have been rendered if it
were not floated. A browser places the top of a floated inline element depending on where
it would have been rendered in a line if it were not floated. If at the beginning of a line, its
top is aligned to the top of the line; otherwise, its top is aligned to the bottom of the line.


Example The example contains eight floats: four spans and four divisions. The four paragraphs
demonstrate each setting of clear. When a float isn’t cleared on the side that it’s floated, it
stacks next to other floats on that side. When cleared on a side, a float or block element
moves below floats on that side.


Related to Static, Absolute, Fixed

Free download pdf