HTML and CSS Reference
In-Depth Information
Figure 8-12.
The 30% and 80% positions of both the element and the background image coincide
Try it yourself by loading position_percent.html into a JavaScript-enabled browser that supports the
<canvas>
element (all modern browsers do). Experiment by changing the percentage values for
background-position
. Figure
8-13
shows that when you change the value to
90% 10%
the top-right 10 percent of
the background image is proportionately distanced from the top right of the element.
Figure 8-13.
The background image is now positioned at 90% horizontally and 10% vertically
Using percentage values for
background-position
can be difficult to understand, but they're particularly
useful in fluid layouts. Background images are visible only within the element to which they are applied, and not
through the element's margins. Any excess is hidden. To demonstrate the effect, fluid.html contains two
<div>
elements, one with its width set to
80%
, and the other set to
60%
. Both use the same background image, which is
1200px
wide. The image consists of a dark gradient that occupies the left quarter. The remaining three quarters is
a light color. The image tiles vertically, and its
background-position
is set to
25% top
. The styles look like this:
#box1, #box2 {
background-image: url(images/fluid_bg.png);
background-repeat: repeat-y;
background-position: 25% top;
height: 30px;
margin-bottom: 20px;
}