Question

Im using an icon-sheet with all my icons in it, and now referencing them in my CSS.

Each icon is 32*32 and is in a grid like this :

AA BB CC DD ...

A1 B1 C1 D1 ......

A2 B2 C2 D2 .......

UU XX YY ZZ ......

etc.

Where AA = icon, A1=hover, A2=active.

It works ok, in the CSS right now its like this :

.icon {

height:32px;

width:32px;

background-image:url('/img/slbuttons.png');

}

.AAicon {background-position:0px 0px;}

.BBicon {background-position:-32px 0px;}

.CCicon {background-position:-64px 0px;}

etc...

What im looking for is somehow to make it abit more simple, the icons doesnt change in size (32*32) so instead of manually writing each of the different icons, i just want to reference that ex. :

AAIcon = x0,y0, BBIcon = x1,y0, CCIcon=x2,y0 A1Icon = x0,y1, etc. etc.

instead of i have to sit and write each 32,64,96,128, etc myself - wasnt it possible to make a (xpos=gridcount*32, ypos=gridcount*32) ?

Reason why i want this is i just changed my icon-pack size and then i have to rewrite ALL those values again, and each block icon/hover/active are actually the same except for the coordinates, would be a big help if i could just have a global varialbe that defines the size and then thats used automatically to adjust the positioning later on.

Dont know if i can that in CSS, maybe thats CSS3 or ?

Im not an expert at all in CSS or WEB development so its probably an easy one.

Was it helpful?

Solution

In pure CSS, no you cannot do math. It is strictly a styling language. There are a few options when it comes to dynamically styling your page.

You can use SASS and LESS, which are their own languages, run through a processor (SASS uses Ruby, LESS uses JavaScript) to generate the stylesheet.

The second option would be to use JavaScript, and for a beginner, jQuery would probably be the easiest option. Once you have included the jQuery source using something like <script src="js/jquery.js"></script> (or alternatively the Google CDN), you are free to utilize the jQuery library in addition to standard JavaScript.

A short snippet to get the height of an image:

<script>
var imgHeight = $('.icon').height(); //remove the height and width from your CSS first!
var imgWidth = $('.icon').width();
</script>

You can then use jQuery to manipulate the CSS dynamically based on the height of the background image:

<script>
var iconA = $('.AAIcon');
iconA.css('background-position','imgHeight');
</script>

jQuery

OTHER TIPS

Yes you can! By using a css preprocessor you can do math, variables and so much more. The two popular ones are SASS and LESS. SASS is gaining a lot of traction and is what I use. Here is a great rundown of it.

http://css-tricks.com/video-screencasts/88-intro-to-compass-sass/

With a css preprocessor you can do exactly what you are talking about. Good luck! And enjoy easier css!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top