Search code examples
cssbackgroundminifybackground-position

How can I minify CSS? Shorthand for property [ background-position ]?


Mix 1 look at the source-code of my site with 19 chars of byte-wasting letters background-position, for the sprite icons positions, and you get a feel of my little frustration on this long word:

background-position

Using it singularly is fine, but when setting hundreds of sprite icons it's just silly byte-wasting. So my question is: is there any smarter shorthand that can replace this long word? If so, it would save me half my page's bytes!

Just have a look at the insanity of it on the pic below...

Cheers and much appreciated!

update:

notice that every single icon has its own, unique icon and unique background offset.


enter image description here


Solution

  • An approach would be to encode the background-position in a class name and then use javascript to convert this into element styling.

    So

     <p class="mnu" style="background-position: 0 -1690px">
    

    becomes

     <p class="mnu bg p$0$-1690">
    

    Then you do something like

    $('.bg').each( function() {
      var elem = $(this);
      var classes = elem.attr('class').split(/\s+/);
      $.each(classes, function(index, classname) {
        if(classname.indexOf('p$') != -1) {
          var coords = new Array();
          coords = classname.split('$');
    
          elem.css('background-position', coords[1]+"px "+coords[2]+"px");
        }
      });
    });
    

    In effective, you've got your own de-minifier there. I'm not saying it's the best way to do it, but it does address your concern of HTML file size (at the expense of rendering time).