Fun With Less: Buttons

Friday, February 10th, 2012

This first of a series of articles that deal with Less CSS we’ll introduce a fun way to turn an element into a button with the help of a sprite graphic. First comes the sprite map:

Sprite Buttons

Each of the buttons are stacked on top of each other and every one has the same height: 27 pixels.

Next comes the Less mixin. This is where the magic happens:

@webroot: ""
.button (@position, @width: 180px) {
    @buttonHeight: 27px;
    display:     block;
    height:      @height;
    width:       @width;
    text-indent: -100em;
    overflow:    hidden;
    border:      0;
    background:  url("@{webroot}/images/buttons-en.png") no-repeat left -(@position * @buttonHeight);

The above code does a number of things worth going over in detail. @webroot is the root URL of the website. Less compiles all CSS into the current page making it necessary to use absolute URLs instead or URLs relative to the CSS file’s path.

Next, is the mixin declaration. It defines two parameters. The position of the button (starting with 0 for button 1) and the width of the button—set to width of the sprite map.

The button height is then hard-coded and the CSS following uses one of the common image replacement techniques.

Finally comes the background attribute. It says, use the image map positioned to the left of the container. The top of the background is determined by the button number (starting with 0) times the height of each button, subtracted from 0. In other words, button 1 will be at top 0, button 2 at top -27, button 3 at top -54, etc.

The resulting mixin is easy to use.

* Makes all buttons of class 'search' use the last image in the sprite set.
* Uses the actual width of the 'search' button graphic to prevent trailing white space.
*/ {
    .button(3, 82px);
* All links of class 'more' use the first button in the set.
a.more {
    .button(1, 91px);

Leave a Reply