CSS: Placing text over an inline image
CSS is a very powerful tool that works best when kept as simple as possible. Unfortunately there are a lot of WYSIWYG applications and other HTML editors that produce CSS that is anything but simple.
A common request is to be able to display HTML text over an image that's already embedded on the page. There are a number of valid solutions using either tables or CSS.
1. Using a TABLE to overlay text on an image
The HTML solution has been possible since Netscape 3 and is fairly simple to implement, but not so flexible as more recent options.
(width)" height="(height)" background="(path to image)" cellpadding="5" cellspacing="0"> (text to appear over the image goes here)
The HTML approach is to set up a TABLE with a background image. Then a single TD is used to display the text. The width and height of the TABLE are set to match that of the background image. This is a valid approach according to HTML standards, but not so good if you look at the resulting code. Why should you have to use a TABLE to handle this kind of layout? Perhaps CSS has a cleaner solution... |
2. 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.
path to image); width: (width)px; height: (height)px;"> (text to appear at the bottom left of the image)
(text to appear at the top right of the image)
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: top, right, bottom 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.
No comments:
Post a Comment