I often want to include computer source code in my blog articles, but source code can be problematic for page layout. Code tends to be unusually wide or unusually long compared to other article content. Spacing and layout of code is specific and significant, so long lines can't wrap as easily as paragraphs of text can.
HTML's <pre> tag tells the browser to use a fixed-width font and preserve all spacing, so it's an obvious candidate for marking up source code. But the default rendering of <pre> can cause problems for the rest of the page. With old-fashioned table-based layouts, a <pre> with a long line in it can push out the width of the table and cause wrapped paragraphs to be as wide as the longest line of code. With layouts based on styled <div>s, by default long lines overflow or underflow the box that contains them, obscuring the rest of the line and possibly other stuff.
Thankfully, CSS provides an elegant solution for managing content that overflows the bounding box:
pre {
overflow: auto;
max-height: 200px;
}
overflow: auto tells the browser that if the block's content is bigger than the allowed space, the browser should give the box scrollbars. This fixes the problem with long lines: If a non-wrapping line is too big for the content box (such as in my two-column design with a sidebar on the right), the <pre> will get a horizontal scrollbar instead of spilling over the edge.
max-height: 200px tells the browser not to let a <pre> take up more than 200 pixels of vertical space. Combined with overflow: auto, long sections of source code will appear in a reasonably-sized box with scrollbars. This lets readers who are skimming the article skip past long code sections in the middle of articles, and keeps the page height reasonable. I have mixed feelings about this technique: For some articles, the code samples are like mathematical equations, not ancillary content, and shouldn't be hidden away. But it's easy to not set a max-height, if you think it's inappropriate.
An example:
\notes \new PianoStaff <<
\new Staff {
\key e \major
\clef treble
r4 \relative c' {
\times 2/3 { e'8 fis cis } \times 2/3 { e b cis }
\times 2/3 { gis b fis } \times 2/3 { gis e gis }
dis2 cis4
}
}
\new Staff {
\key e \major
\clef bass
\relative c, { e8 b' e gis b gis e b e, cis' e gis cis gis e cis }
}
Update: Anyone who saw this little article on the day it was posted saw me freak slightly when I noticed at the last minute that my stylesheet changes didn't seem to work in some browsers. The problem was entirely user error, and had nothing to do with browser compatibility. All better now.