Last Updated: February 25, 2016
· liquidise

What CSS Needs: Granular Positioning (part 2)


read more at: Ben Roux's Blog

Background-Position-X, Background-Position-Y

Background positioning is a strong case for seperating a grouped rule into individual parts. Why include x, y positioning exclusively as a rolled-up modifier? What is the danger in breaking out the properties as is done with margin or padding? Even more confusing, is this has been supported in IE since version 5.

As with any spec suggestion, there are many applications to this. A clear example arrises when a UX designer ships you a single .png containing many icons for a single page:


To style this today, we need something like this:

.volumeDown       { background-position: 0px 0px;     }
.volumeDown:hover { background-position: 100px 0px;   }
.volumeUp         { background-position: 0px 100px;   }
.volumeUp:hover   { background-position: 100px 100px; }

An obvious pattern emerges. All the hover state does is shift the background by 100px. The programmer in all of us wants to abstract this. But, today, we cannot. We are left to create 2 classes for each icon. If this graphic included a down state, we would need a third class for each icon.

If given the ability to break this up, we can abstract these properties and clean them up rather easily.

.icon      { background-position-x: 0px;   }
.icon:hover{ background-position-x: 100px; }
.icon.volumeDown{ background-position-y: 0px;   }
.icon.volumeUp  { background-position-y: 100px; }

Here, we are only adding a single class per icon, instead of 2 (or 3 with a down state). For a small image, like this example, the change is nominal. For larger collections, this can save 10 or 20 classes.

As many will note, this was suggested for CSS3, but was unfortunately dismissed on the grounds that it was "too weak to introduce new properties for".