Reusable ‘Controls’ with Sprites, CSS, and Spark Partials

I came across SilkSprite during some of my work with BluePrintCSS and fell in love. I’ve used the FamFamSilk icons for ages and, with a current project, wanted to implement some instant CSS buttons and menu items using those icons.

So, with CSS-fu in hand, here’s how the button turned out.

First, creating a simple CSS button style:

.button

{

display: inline-block;

font-weight: bold;

font: bold .85em/2.5em Verdana, Helvetica, sans-serif;

text-decoration: none;

text-indent: 10px;

width: 150px;

height: 2.5em;

color: #555555;

background-color: #EAEAD7;

border: #CCCCCC solid 1px;

-moz-border-radius: 5px;

-webkit-border-radius: 5px;

}

.button:hover

{

background-color: #F3F3E9;

color: #737373;

cursor: pointer;

}

This button is pretty simple and standard—nothing fancy. The most important tag in there is display: inline-block as this allows our buttons to share the same row and not stack on top of each other (like float:left would cause).

Hover Off:

Hover On:

Second, because I needed to include the icon INSIDE another container (the button), I modified the original SilkSprite ss_sprite and removed a bit of the extra padding.

.sprite

{

display: inline-block;

overflow: hidden;

background-repeat: no-repeat;

background-image: url(/content/img/sprites.png);

padding-left: 25px;

padding-top: 2px;

height: 16px;

max-height: 16px;

vertical-align: middle;

}

The important thing to note here is the padding-top and the height attributes. Until I’m lead into the light and improve my CSS-fu, I’m compensating for the font height differences by using padding-top. e.g. I want the icon to truly show up in the “middle”… and vertical-align just wasn’t pushing it far enough.

We’ll come back to actually working with SilkSprite in a moment, let’s work up a quick Spark partial view to display our results. Now, you could do this without the partial views—just replace my Spark variables with the actual text we’re passing to them. I’ll provide both examples.

Our button needs three elements to be useful:

An ID so that we can call it from jQuery or your client-side query engine of choice,

A Sprite Name, such as ss_add, etc. These are provided by SilkSprite.

The button text.

So, knowing that, a basic button could be rendered using:

<divid=”my-button” class=”button”>

<spanclass=”sprite ss_add” />Add Activity

</div>

We can simply substitute out the variable elements (id, sprite class, and text) and create a Spark partial view (named _styledButton.spark and located in the /Shared view folder).