I’m hoping there will be a CSS guru out there that can help with this one…
I’m building a responsive layout for a site which includes a horizontal navigation bar across the top. This bar contains 5 buttons each of the same width (although obviously this width needs to be flexible). I would like to use icons instead of text for the buttons for when the menu is viewed on a device with a small viewport width. I will use media queries to adapt the layout to use text once I feel the viewport width has reached a suitable size. This is important because I am not anticipating needing to change the size of the icons themselves. I’m happy for them to be of a fixed size, centered in the button and if the button size itself changes then there will simply be more “padding” around the centered icon.
Ordinarily I would use have all the icons in one image and use the sprite technique to only display the correct part of the image, but I have come across a problem. If I want the anchor element to fill the parent list element then how can I center the sprite?
Here is some example markup:
First the html (snippet)
<nav>
<ul class="top_nav">
<li><a class="link_1" href="#">link 1</a></li>
<li><a class="link_2" href="#">link 2</a></li>
<li><a class="link_3" href="#">link 3</a></li>
<li><a class="link_4" href="#">link 4</a></li>
<li><a class="link_5" href="#">link 5</a></li>
</ul>
</nav>
And I might style it like this:
nav ul {
width: 100%;
overflow: auto;
}
nav li {
float: left;
width: 20%;
background: #2c2c2c; /* dark background for light icons */
}
nav li a {
display: block;
border: 1px solid #e7e7e7;
background-image: url(path/to/sprite.png);
background-repeat: no-repeat;
text-indent: -15000px;
width: 48px;
height: 48px;
margin: 0 auto;
}
nav li a.link_1 {
background-position: 0 0;
}
nav li a.link_2 {
background-position: 0 -49px;
}
etc….
But this will only give me a clickable area of 48px x 48px within a button that can change it’s width depending on the size of the parent element. If I make the anchor element fill it’s parent list element then the icon can’t be centered using the margin rule.
I could add another element inside the anchor element which was empty but had the icon as it’s background like this:
<li><a href="#"><div class="link_1">Link 1</div></a></li>
And style it with:
nav li a {
display: block;
border: 1px solid #e7e7e7;
width: 100%;
}
nav li a div {
background-image: url(path/to/sprite.png);
background-repeat: no-repeat;
text-indent: -15000px;
width: 48px;
height: 48px;
margin: 0 auto;
}
nav li a div.link_1 {
background-position: 0 0;
}
But this isn’t a very semantic or elegant solution. Can anyone think of anything better??
You can use:
:before/:after) instead of real elements to keep code clean;background-sizeproperty to zoom your background images;