Reputation: 702
CSS novice here. I've been asked to implement a sprite for a menu, six options in a 3 x 2 grid that are directly adjacent to one another in the .png file. Each sprite is 20px by 20px (and the whole file is thus 60px by 40px), but the menu button needs to be 28px by 28px, i.e., with a padding of 4px.
If I implement this padding as-is, then the neighboring sprite images will appear in my padding. So instead I'm using a border, which allows me to specify the actual background color behind the menu item and thus conceal the other sprites.
Here is an attempt (using SCSS):
$background-color: #fff;
/* The background in question is actually a darker grey,
but I'm using white for simplicity's sake. The real background color
will be detected. */
.nav-home {
background-image: url('http://3.bp.blogspot.com/-z7fLYYhBwYk/VK08xu5q00I/AAAAAAAAIAg/_AR083a5biY/s1600/Screen%2BShot%2B2015-01-07%2Bat%2B15.03.31.png');
width: 20px;
height: 20px;
background-repeat: no-repeat;
background-position: -40px -40px; //variable
padding: 0px;
border: 4px solid $background-color; // my de-facto padding
border-radius: 3px; // a radius that belongs to the actual border
&:hover{
// ** padding? **
border: 1px solid #e6e6e6;
//border-radius: 3px; //this is how my border needs to look if I could specify a padding color
}
}
(the image I used here is just for the sake of illustration)
Since I don't know how to specify the background color of the padding, I have made a de-facto padding using the border attribute instead. Unfortunately, the button also needs to have a border in its own right, one which is only visible on hover. Do I need to create a second border somehow? Or can padding indeed be styled separately from the image itself?
Corollary question: is it standard procedure to ask the designer to pad the original sprite file for me? Or is this a common problem with a well-trodden solution?
Upvotes: 1
Views: 514
Reputation: 5696
I'd recommend you use generated content with CSS. You can then set the size, position and background of that generated element. Basically, you can style it like you would any other element. So you can effectively 'crop' out the part of the sprite you need. In this example I'm using :before
$background-color: #fff;
.nav-home {
width: 28px;
height: 28px;
padding: 0px;
position: relative;
border-radius: 3px; // a radius that belongs to the actual border
border: 2px solid #0cf;
&:before {
background-image: url('http://3.bp.blogspot.com/-z7fLYYhBwYk/VK08xu5q00I/AAAAAAAAIAg/_AR083a5biY/s1600/Screen%2BShot%2B2015-01-07%2Bat%2B15.03.31.png');
width: 20px;
height: 20px;
outline: 1px dotted #f0f;
content: '';
display: block;
background-repeat: no-repeat;
background-position: -38px -38px; //variable
position: absolute;
top: 4px;
left: 4px;
}
}
http://codepen.io/goshdarnheck/pen/MwjZyR
I've added an outline on the :before
element to make it clear what it is and where it is.
Upvotes: 2