Text Blocks Over Image
The idea is just to overlay some text over an image, but as blocks that stick out from the left with an even amount of padding all the way around the variable-length text. Here is a screenshot example:
The Schematics
The HTML
1 2 3 4 5 6 |
A Movie in the Park: |
Putting the image in as a background image of the wrapping div would be easier, but in this scenario I see the images as content, and thus belongs in the HTML. We’ll use that wrapping div as a container for absolute positioning.
The CSS
1 2 3 4 5 6 7 8 9 10 11 12 13 |
.image { position: relative; width: 100%; /* for IE 6 */ } h2 { position: absolute; top: 200px; left: 0; width: 100%; } |
This is going to put our text right up on top of the image nicely, but it doesn’t accomplish the transparent black box we want to achieve behind the text. For that, we can’t use the h2, because that is a block level element and we need an inline element without an specific width.
Let’s wrap the inside h2 of the in a span:
1 2 3 |
A Movie in the Park: |
The use that span to style the text and background:
1 2 3 4 5 6 7 8 9 10 |
h2 span { color: white; font: bold 24px/45px Helvetica, Sans-Serif; letter-spacing: -1px; background: rgb(0, 0, 0); /* fallback color */ background: rgba(0, 0, 0, 0.7); padding: 10px; } |
Problem
When an inline element breaks, the block breaks immediately after the last character in the line, and begins immediately flush left on the next line. Padding, in this case, does not help us.
To solve this, we’ll apply some more spans on either side of the
element to simulate that padding.
1 2 3 4 |
A Movie in the Park:Kung Fu Panda |
Those new spans we’ll use to apply padding:
1 2 3 4 5 |
h2 span.spacer { padding:0 5px; } |
Fixing Semantics
At this point the design is accomplished, but there there is an awful lot of extra HTML elements added purely for design reasons. Namely, all those spans. jQuery can jump in and save us here. Simply remove all the spans from the markup, and dynamically apply them like this:
1 2 3 4 5 6 7 8 9 10 11 12 |
$(function() { $("h2") .wrapInner("") $("h2 br") .before("") .after(""); }); |