Background color for inline text
In searching for a solution to a CSS problem I had I stumbled over anotherA interesting problem, similar to mine. Most people seemed to agree that it
was impossible to do in pure CSS. The effect those people were afterA is commonly used in magazines where text with a background color is putA over an image. A simple effect hard to achieve.
One solution was to surround each line of text using styled span elements. AnotherA solution usedA a€a teeny weeny jquerya€ to solve the problem. I'm sure it's a solid solution but using jquery andA javascript to be able to style text is, well, wrong. ForcingA editors to add invisible span elements in text is also not a good idea. But -A the effect can actually be achieved using css only and still keep the html simpleA and semantically correct.
If you use a block element, like
, and set the background color, it will be A a filled square behind the text. By setting the css display property to inlineA you get A close to the effect wanted.
So far it is simple. The problem then is that using padding on inline text willA only affect the horisontal padding (text indentation) on the first and lastA line of text. You get the following effect.
In order to get the effect we want we need to add two elements. A surroundingA block element (div) surrounding the paragraph and an inline element (span)A surrounding the text inside the paragraph. Both of which is semanticallyA without meaning.
First we add a left border on the surrouding block element. Then we move theA text in the span element slightly to the left. The background color is setA on the paragraph and does not move. Using this neat little trick we simulateA text padding or indentation on each line of text.
Finally we need to fix the vertical padding and line height to get rid of theA spacing between the text lines. The end result is not perfect. There are stillA problems when the user resize text and you need to be careful with the spacingA in Internet Explorer. But it's a good start.
Chrome sometimes change line height seemingly in a random fashion when insertingA html
. Setting white-space to pre-line fix this behaviour.A If not for Internet Explorer it could be simplifed further. Internet Explorer doesA not seem to support white-space: pre-line. So Internet Explorer still needs manuallyA added html breaks.
The full source
div#column { border-left: 6px solid #000; } p.subs { display: inline; font: bold 14px/18px arial; color: #fff; background: #000; padding: 1px 0 1px 0; white-space: pre-line; /* Not understood by IE, use manual br for IE */ } p.subs span { position: relative; left: -3px; } p.subs br { display: none; }Ground round
salami pig, meatball short loin frankfurter
short ribs pork hamburger rump
strip steak beef ribs T-bone salami ham hock.
Truncated by Planet PHP, read more at the original (another 2093 bytes)


