HTML and CSS Reference
In-Depth Information
Specifying Backgrounds for Elements
The CSS background properties can be used to apply a background to any block-level
element—a
<div>
, a
<form>
, a
<p>
, a
<table>
, or a table cell. Specifying the back-
grounds for these elements is the same as setting the background for an entire page, and
is an easy way to add decorative elements to a page. For example, I want to add an arrow
to the left of all the major headings on my web page to really emphasize them. I could
stick an
<img>
tag inside each of the
<h1>
elements on my page, but that would be repet-
itive, and the images don't make sense as part of the contents of the page. So instead, I
can apply the images using CSS. The results are in Figure 9.20.
9
Here's the style sheet:
<style type=”text/css”>
h1 {
background: url(arrow_right.png) no-repeat center left;
line-height: 60px;
padding-left: 60px;
}
</style>
The heading tag is completely normal:
<h1>This Heading Has a Background</h1>
FIGURE 9.20
A heading with an
image background.
In the style sheet, I use the
background
property to specify the background image and its
position for the
<h1>
tag. One extra benefit is that this style will be applied to all the
<h1>
tags on the page. I use the
background
property to specify the image and to posi-
tion it. I use
no-repeat
because I want only one copy of the image and
center left
to
position it at the left end of the header, in the middle. I use the
line-height
property to
make sure there's plenty of space for my background image, which is 50 pixels tall,
regardless of the font size of the heading. Then I add 60 pixels of padding to the left of
the heading so that the text will not appear over the background image.