treehouse : what would you like to learn today?
Web Design Web Development iOS Development

Incrementing a value in pure CSS

  • I remember stumbling across a way to increment a value using just CSS but it's slipped my mind.

    I have a large sprite sheet, each item has three states.

    When I roll over the sprite when it is being used, I want something like this.


    a {
    background-position: 0, 50px;
    }

    a:hover {
    background-position: +=50px, +=0;
    }


    As you can see I'm trying to use the addition operator from js here to try and illustrate my point.

    Does anyone have any idea how to do this without javascript....? I just can't seem to remember and it's driving me crazy.

    I don't mind if you can't solve the problem but can help me with the increment problem.

    P.S. This is not an "counter increment" question ;)
  • Not currently possible unfortunately (due to poor browser support). I assume the experimental feature calc() is what you are referring to (https://developer.mozilla.org/en/CSS/calc)?
  • I'm not sure what are you trying to do...
    Trying to guess and playing with background-origin I did this for two states... (no ie compatibility for older than 9)...
  • There is a css3 counter... like adding line numbers to a pre tag
    pre { counter-reset: line; }
    pre::line-marker { counter-increment: line; content: counter(line) "."; }
    But I don't think it'll do what you want with a three-state background image. You might need to use some javascript.
  • Yes, it is calc() that you're referring to, I think, here's a table of it's support: http://caniuse.com/#feat=calc
  • OK guys thankyou so much for your help on this. I must be mistaken in thinking this was possible in CSS2. I was positive I had achieved this before without the use of javascript, but hey, if no one else knows about it, I must be wrong.

    This was my first post here, and I am really impressed with the quality of the responses.

    @xpy: Tried your link in Chrome and Chromium but just got a blue page. In Firefox 11, saw the site but couldn't see the mario link. Appreciate the effort though... :)
  • And just to clarify WHY I wanted this functionality, it is because I auto generate the sprite sheet CSS, and then I wanted one rule to apply to all elements using this sheet.

    So, every .sprite would have 50px added to it's current y-background-position on :hover, which of course would be released on mouse out. I would not know the original background position of the sprite, merely that it needs to move 50px down from it's current position.

    Happy styling!
  • :D I knew something would go wrong!
    I'll link it again...
    HERE it is as a dabblet
    and HERE it is as a JSFiddle
    I hope you can see it and it helps you :D
  • Cheers xpy, very cool of you.