I always feel that the CSS background image positioning Some specious, this problem has plagued me for a long time, today finally understand, must be written down to prevent forgetting.
In CSS, the background image is positioned in 3 different directions:
1 keywords: background-position:top right;
2) pixel: background-position:0px 0px;
3) Percentage: background-position:0% 0%;
The above three sentences, the picture is positioned in the upper left corner of the background, on the surface to see the effect is the same, in fact, the third positioning mechanism and the first two completely different.
The first two positioning, are the background image of the upper left corner of the original point, placed in the specified position. Take a look at the figure below, the specified position is "20px 10px" and "60px 50px", are the origin of the picture in that position, the figure is represented by X.
But the third kind of positioning, that is, percentage positioning, is not the case. Its placement rule is that point of the picture itself (x%,y%), coinciding with that point of the background area (x%,y%). For example, if the placement position is "20% 10%", the actual result is shown below, and you can see that this point is located in the "20% 10%" position of the picture itself.
Here is an interesting example.
The background picture is four side-length 100px squares stacked together:
How can I bring it across:
The answer is to set up four div areas in the Web page:
<div class="box1">
</div>
<div class="box2"">
</div>
<div class="box3">
</div>
<div class="box4">
</div>
Then, write CSS like this:
.box1, .box2, .box3, .box4 {
float:left;
width:100px;
height:100px;
position:relative;
background: #F3F2E2 url(1234.png) no-repeat;
}
.box1 {
background-position:0% 0%;
}
.box2 {
background-position:0% 33.33333%;
}
.box3 {
background-position:0% 66.66666%;
}
.box4 {
background-position:0% 100%;
}
Click here to see the final effect. You can see the settings for the second and third squares, which are not generally imagined as "0% 25%" and "0% 75%".
But to be honest, this example is easier to set with the pixel method. The main advantage of using the percent setting is that when the page is scaled, the background picture is scaled along with it.