Pro HTML5 and CSS3 Design Patterns

(avery) #1
CHAPTER 4 ■ BOX MODELS

Floated Box


Problem You want to style the box of a float.


Solution You can float any element using float:left or float:right. A float is removed from the
normal flow and placed above the borders and backgrounds of adjacent blocks. This shrinks
the float’s parent and collapses it completely when all its children are floated. Even though a
float is removed from the flow, it indents adjacent content in the flow. Left floats indent
adjacent content to the right, and right floats indent content to the left. A float is positioned
vertically at the location in which it would have been rendered in the normal flow. It is
positioned horizontally inside its parent’s padding area on the left or right. A float stacks
next to other floats in the same general vertical location. When a float cannot fit next to
another float, it moves down below it. A float’s position, size, padding, borders, and margins
affect the position of adjacent floats and adjacent inline content. The precise location of a
float cannot be predetermined.
width sets the width of the float. width:auto is the default value and shrinkwraps the float
to fit the width of its widest line.
height sets the height of the float. height:auto is the default value and shrinkwraps the
float to the height of all its child blocks or lines.
margin has unique float features. A positive margin pushes the float away from its point of
alignment and pushes other floats and inline content away from it. A negative margin pulls
the float to the other side of its point of alignment and pulls other floats and inline content
closer. Margins around floats do not collapse.
border and padding expand the outer size of a float. The left border and padding of a left
float move the float to the right, and its right border and padding move other floats and
inline content on the right further to the right. This applies vice versa for right floats. Top
border and padding move the float down. The bottom border and padding move down any
floats below the float, and extend the float’s effect on adjacent content in the normal flow.


Pattern SELECTOR { float:LEFT_RIGHT; width:+VALUE; height:+VALUE;^
z-index:+VALUE; margin:±VALUE; padding:+VALUE;
border:+WIDTH STYLE COLOR; background:VALUES;
overflow:VALUE; visibility:VALUE; }


Location This design pattern applies to all elements.


Example The three floats in the example are removed from the flow, which brings together the static
BEFORE and AFTER boxes and shrinks the height of the floats’ parent. The three floats stack
next to each other from left to right. The AFTER text is moved to the right by the last float.
Margins, borders, and padding expand the floats’ outer boxes and push away other floats.


Related to Display, Box Model; Width, Height, Sized, Shrinkwrapped, Stretched (Chapter 5); Margin,
Border, Padding, Background, Overflow, Visibility (Chapter 6)

Free download pdf