Blog >

Just one CSS class for darker button hover states across your whole site

Today I figured out a simple and easy way to enable dark button hover states for all my HTML buttons, with the use of just one CSS class.

The one requirement is that your button HTML has another HTML element inside the actual button so that we can add the ‘darker hover’ to this inner element, and that this inner element is the full width of the ‘a’ tag. Say you have the following HTML for your button:

<a href="directory/file.html" class="btn">
    <div>Submit</div>
</a>

And the CSS for your button is something like this:

<style type="text/css">>
    .btn { 
            color:#000;
            background-color:#ccc;
            border: 1px solid #666;
            border-radius: 5px;
            padding: 5px 30px;
    }
</style>

All you need to do to to add a darker hover state to your button is add one style to your CSS:

<style type="text/css">>
    .btn:hover > div {
        background-color:rgba(0, 0, 0, 0.1);
    }
</style>

This simply shows a transparent ‘shade’ of black over the top of your button’s background colour, giving the effect that on ‘hover’, the button becomes darker. The beauty of this is that it saves you from having to add a hover style for each of the different button styles in your CSS file – you’ve got a ‘one class covers all’ solution.

Easy! And it degrades gracefully in older browsers (it has no effect).