The other day, I needed to add a strap line or caption on top of an image. Yes, I can do this in an image editor like Photoshop or Fireworks but I wanted to compare an alternative method using CSS. The CSS method also has the advantage that the text will be read by search engines. Anyway, here’s how I chose to to do it.
In order to place text on top of an image, I could simply use a background image on my (X)HTML element and add the text. This works if the image is purely decorative. In my case, it’s not. The image is in the (X)HTML. That means I need to use some other method. This is the (X)HTML that we want to use.
<div class="image-wrapper">
<img src="someimage" alt="sometext" />
<p>The text is in a paragraph tag</p>
</div>
It’s pretty standard. The image and it’s associated text are contained in a <div> with a class called image-wrapper. Without any other styles, the paragraph will follow the image because it’s a separate element. Now, here’s the trick that we need to place the text over the image. In our style sheet, in order to position the text in relation to the containing <div>, we need to assign position: relative to the <div> and assign position: absolute to the paragraph. Then, we position the paragraph in the normal way for absolute positioning. The position: relative on the <div> is needed in order to give a new positioning context for our absolutely positioned text/paragraph. If we did not have this, the paragraph would be positioned relative to the next nearest containing block [possibly the body element] and that’s not what we want here. Here’s a short reminder about the CSS position property.
Here’s my simple example which illustrates the method [with a few other paragraph/text styles added]. In this case, I positioned the text near the top of the image. The CSS is here:
.image-wrapper {
position: relative;
width: 250px;
}
.image-wrapper p {
position: absolute;
left: 0;
top: 0;
padding: 10px;
border: 1px solid #FFF;
width: 218px;
color: #FFF;
margin: 5px;
}
Of course, there’s more that could be done with this. Perhaps a semi-transparent background image on the paragraph would give it more pizazz? Or, maybe rounded corners using the CSS3 border radius property? However, that’s a subject for another day.
Powerful and flexible ecommerce shopping cart software from Ecommerce Templates
Join SugarSync for online backup. Sync your files between Mac, PC and mobile phone. Get 2 GB FREE and up to 10 GB bonus space!
Handcrafted CSS: More Bulletproof Web Design by Dan Cederholm and Ethan Marcotte is a book that describes CSS3 methods that work in today's browsers. You’ll be convinced that now is the time to start using CSS3. Learn how to create flexible, reliable and bulletproof websites with the latest CSS methods!
Buy from Amazon.com · Amazon.co.uk