Pregunta

For an application with a good lot of icons, I want to make an image sprite. Since I started my 'adventure' in the land of webdesign/ front-end webdev, I've always wondered: what is the logic behind background-position: (left)<number>px (top)<number>px;

When you compare this to the shorthand property for either padding or margin(when only specifying top and left), these are both property: (top)<number>px (left)<number>px; So top and left values are reversed.

Also, suppose I have a sprite that is 64px (length) x 16px (height) and contains a total of 4 16x16 icons. To get the second icon in the sprite (|____|_this_|___|____|), you have to type background-image: -16px 0px; instead of 16px 0px (which would be logical, because the second icon starts 16px later than the first one).

If you want an example (I know w3schools is not always correct but it will do for the example): http://www.w3schools.com/css/tryit.asp?filename=trycss_sprites_nav

So my question is: Why are all the values for the background-position property like,... reversed? Is there any logic behind it? Does CSS read the property from right to left?

¿Fue útil?

Solución

When using shorthand for margin (or padding) with only two values you are not setting a X/Y position - you are setting four margins, using the same value for top & bottom (vertical margins), as well as right & left (horizontal margins). You can also pass four values and they will start with margin-top and continue clockwise around the box (top -> right -> bottom -> left).

I usually remember this using the word "trouble" without any vowels (TRBL).

Anyway: for positioning there is only two values, and it is common practice to use the vertical axis (x-axis, 0 is top) and then then horizontal (y-axis, 0 is left), so using a negative value for the y-axis on background-position would move a background the same direction you would move the box if you were to give it a negative left margin.

.class1 {
    background-position: -20px 0; // move background 20px left
    margin-left: -20px; // move box 20px left (margin, following items will also move)
}

.class2 {
    position: relative;
    left: -20px; // move box 20px left (position, following items will stay put)
}

So I guess what I'm trying to say is that the values are basically coherent, depending on how you look at it ;)

Docs for margin (check the syntax list)

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top