Pro HTML5 and CSS3 Design Patterns

(avery) #1
CHAPTER 5 ■ BOX MODELS EXTENTS

Width


Problem You want to set the width of an element to size it, shrinkwrap it, or stretch it.


Solution CSS provides the width property for this purpose.
This design pattern is an introduction to the Sized, Shrinkwrapped, and Stretched design
patterns. The purpose of this design pattern is to compare how width applies to all six main
types of boxes: inline, inline-block, block, table, absolute, and floated. This comparison
makes it easy to choose the proper combination of width, element, and display box to create
the layout you want.
width works on all types of elements except for inline elements. width works differently
depending on the type of element and whether it is positioned or floated. width is
completely independent from height. width:auto is the default.


width:auto width:auto horizontally shrinkwraps the following boxes: inline, inline-block, floated, table,
and absolute (when both left and right are auto).
width:auto horizontally stretches block boxes and absolute boxes (when left and right are
both set to a value, such as 0 ).


width:+VALUE You can size an element by assigning pixels, ems, a percentage, or another fixed
measurement to width. Fixed-width elements may not be user-friendly when the viewport is
much larger or much smaller than expected. Percentages are more flexible because they can
scale to the viewport.


width:100% width:100% stretches an element to the width of its parent, but unlike auto, width:100% has
limitations. A browser does not automatically adjust the width to keep the element
stretched. An element’s horizontal margins, borders, or padding can expand its width
beyond the width of the parent.


Pattern SELECTOR { width:+VALUE; }


Location width applies to all elements except for inline elements.


Tips A browser ignores width on a static inline element because font and font-size determine
the width of its text, which sets the element’s width.
Tables stretched using width:100% work almost as well as horizontally stretched absolute
elements. When you assign borders or padding to a table, the outer box of a table does not
expand, and the table does not overflow its parent. This is because borders and padding are
rendered on the inside of the table and do not expand its outer box. On the other hand, a
margin assigned to a table will reposition the table, and it will overflow its parent.


Example The example illustrates all ways of using width to create horizontally shrinkwrapped,
stretched, and sized elements. I omitted nonessential CSS rules and the HTML code to fit the
example on one page. The text in the element is the name of its class. The replaced element
is an image of a star.


Related to Sized, Shrinkwrapped, Stretched; Static, Absolute, Float (Chapter 7); Table (Chapter 15)

Free download pdf