Pro HTML5 and CSS3 Design Patterns

(avery) #1
CHAPTER 11 ■ SPACING CONTENT

Preserved


Problem You want to selectively preserve whitespace around text and objects that you insert into
the HTML document. For example, you want to preserve whitespace in code. You also
may want to insert specific amounts of whitespace into your document without having to
track the number of
elements and   entities you need to insert to achieve
the desired effect.


Solution When whitespace is an intrinsic part of the content, you can mark up the content with


 to preserve the whitespace. This identifies whitespace as part of the content and
preserves it.
 also works in non-CSS browsers.
When whitespace is decorative or when you cannot use
, you can use white-
space:pre to prevent whitespace from being collapsed.
You can assign white-space:pre to a span containing nothing but whitespace to direct
the browser to render that whitespace—although this is probably not a good idea, as
explained under “Disadvantages.”

Pattern^


HTML

 CONTENT 
^


CSS SELECTOR { white-space:pre; }^
SELECTOR { white-space:normal; }


Location white-space:pre applies equally well to any type of element.


Advantages white-space:pre has several advantages over

. It can preserve whitespace in
existing markup that you cannot modify to include
. It allows preserved whitespace
to intermingle with images, objects, and any other type of element. (The HTML
specification prevents
 from containing , , , , , and
.) It does not automatically style the content with a monospace font like
. It
can preserve whitespace in an inline element. (Since
 is a block element, 

cannot be embedded in paragraphs, headings, and other terminal block elements.)
Lastly, it can turn whitespace on and off selectively.


Disadvantages Since it is unusual for whitespace to be preserved in HTML markup, it is easy to
accidentally change the layout of the document just by rearranging a little whitespace in
a preserved element.
Most HTML authoring software and utilities automatically rearrange whitespace to make
code more readable or to remove whitespace to reduce document size. These programs
break preserved whitespace in elements styled with white-space:pre, but most retain
whitespace in

.


Tip You can use white-space:normal to override a rule that applies white-space:pre to an
element. white-space:normal is the default.


Related to Nowrap, Code; Inline Elements (Chapter 2)