CSS3 Suggestion

Is it too late to request something like ‘background-position-x’ and ‘background-position-y’ to be added to the CSS3 spec? These would be extremely useful in cutting down the amount of code needed when the X position of the background needs to be as previously set but the Y needs to be changed.

This is useful for sprite techniques. For example, say you have a single image with a bunch of icons in a matrix. Different icons are represented horizontally in the image and different styles of those images (e.g. hover, selected,disabled) are represented vertically. So, now you can style all elements that contain icons with the ‘icon’ class which defines the background-image. Then add an additional class to each of these based on which icon it represents, which would change the background-position-x to display the appropriate icon image. Finally, you would have addition rules that define current state of the icon, such as a ‘select’ class or a ‘.icon:hover’, which would change the background-position-y.

An example of 5 icons with 3 states (e.g. normal, hover, selected) would require 15 different rules as follows:

.icon {
  background: url('images/icons.png') 0 0 no-repeat;
  width: 16px;
  height: 16px;
}
.icon1:hover {
  background-position: 0 -16px;
}
.icon1.selected {
  background-position: 0 -32px;
}
.icon2 {
  background-position: -16px 0;
}
.icon2:hover {
  background-position: -16px -16px;
}
.icon2.selected {
  background-position: -16px -32px;
}
.icon3 {
  background-position: -32px 0;
}
.icon3:hover {
  background-position: -32px -16px;
}
.icon3.selected {
  background-position: -32px -32px;
}
.icon4 {
  background-position: -48px 0;
}
.icon4:hover {
  background-position: -48px -16px;
}
.icon4.selected {
  background-position: -48px -32px;
}
.icon5 {
  background-position: -64px 0;
}
.icon5:hover {
  background-position: -64px -16px;
}
.icon5.selected {
  background-position: -64px -32px;
}

Whereas with the background-position-x/-y properties it would only need the following 7 rules:

.icon {
  background: url('images/icons.png') 0 0 no-repeat;
  width: 16px;
  height: 16px;
}
.icon2 {
  background-position-x: -16px;
}
.icon3 {
  background-position-x: -32px;
}
.icon4 {
  background-position-x: -48px;
}
.icon5 {
  background-position-x: -64px;
}
.icon:hover {
  background-position-y: -16px;
}
.icon.selected {
  background-position-y: -32px;
}

Of course, the more sprites used the more redundancy is needed without the use of a background-position-x/-y. Without separate X and Y properties it takes i*s rules, where i represents the number of icons and s represents the number of states. With them it would only take i+s-1. The benefits are obvious.

Leave a Reply

Your email address will not be published. Required fields are marked *