Using CSS to overlay text on an image

Indeed there is a simpler, more flexible solution. Instead of a TABLE we use a DIV and CSS positional attributes to place futher text and images with relation to that DIV.

<div style="position: relative; background: url(path to image); width: (width)px; height: (height)px;"> <div style="position: absolute; bottom: 0; left: 0.5em; width: 400px; font-weight: bold; color: #fff;"> <p>(text to appear at the bottom left of the image)</p> </div> <p style="position: absolute; top: 1em; right: 2em; width: 120px; padding: 4px; background-color: #fff; font-weight: bold; font-size: 11px;"> (text to appear at the top right of the image) </p> </div>

As you can see, we are able to place any number of sub-elements within the surrounding div. In this case a div containing paragraphs with text (bottom left), and a paragraph by itself (top right).

The CSS approach is to use one DIV to define the area where the background image appears. This DIV has it’s position attribute set to relative in order that the items it contains can be properly placed.

This is done by setting the position attribute of contained items to absolute and placing them by setting one or more of the positional attributes:toprightbottom and left.

This block has been positioned at the top, right

The position attribute may seem complicated at first, but it’s the key to implementing complicated layouts without excessive amounts of code. Remember that you need to have a container element with it’s position attribute set to relative in order to layout subsequent content using absolute positioning.

Without a container element all positioning will be in relation to the viewport (the bottom of the screen). This in combination with position: fixed can create elements that stay in one corner of the screen and don’t move when the page scrolls, but only in browsers other than Explorer. On this site you might see a [top] link doing just that if you’re using a compatible browser.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s