In a website I'm coding, the designer wishes to have ragged-right text with a background color (over a photo). The design prescribes some padding on both the left and the right side and also a well balanced background: all background "blocks" have the same height and stack tightly on top of each other. The following image shows an example.
Searching for solutions for this, it turned out that this design has two distinct challenges:
Make sure that any left and right padding are applied to all lines; and
Make sure that the vertical spacing is perfect.
Challenge 1 can be solved using some css-tricks on multi-line-padded-text. This has also been discussed here on SO on several Q&A's: span background-color & padding problems, CSS create padding before line-break, to link some.
Challenge 2 is a bit trickier and is also related to the box-shadow
-solution for the left and right padding on all lines.
First on this last point: even after carefully setting top and bottom padding to the text, I notice subtle errors (in Firefox, which is definitely one of the targeted browsers):
These subtle lines may also occur between (some of) the lines upon zooming. This would be indicative of a non-exact line-height (thus padding). However, setting the vertical padding too much (to be on the safe side) also has problems:
I used a semi-transparent background (and box-shadow) here to highlight the issues. First, the solution will not work for cases where transparency is needed. And second: the background "blocks" are not anymore of equal height (e.g. the gap between lines 2 and 4 is much narrower than line 4).
It turns out that there exists an inherent problem with setting the right padding: it cannot be predicted exactly how high the actual line-height
is (i.e. not without digging very deep into the internals of the font metrics). Especially in cases where the font used is not predictable (which is common on the web).
So the question is, how to add a background-color to a flowing piece of text, having it properly left and right padded, and having the lines to stack exactly on top of each other?
Some caveats:
Setting
display: inline-block
is a no-no: it will create a rectangular background.The afore-mentioned solutions work "a bit", which is not enough. They have their issues, as illustrated.
Obviously, I am looking for a css-only solution, NOT javascript.
Of course, the text used is server-generated and can change.
I have found one solution which works for me: using a background image of the right color, which can be scaled to exactly one line-height. I will submit this self-answer. Although I do like the hack, I am still open for other suggestions.