How to make a hover effect for pseudo elements?

Nils_e picture Nils_e · Jan 16, 2012 · Viewed 58.1k times · Source

I have a this setup:

<div id="button">Button</div>

and this for CSS:

#button {
    color: #fff;
    display: block;
    height: 25px;
    margin: 0 10px;
    padding: 10px;
    text-indent: 20px;
    width: 12%;
}

#button:before {
    background-color: blue;
    content: "";
    display: block;
    height: 25px;
    width: 25px;
}

Is there a way to give the pseudo element a hover effect such as #button:before:hover {...} and is it also possible to get the pseudo element to hover in response to another element being hovered like so: #button:hover #button:before {...}? CSS only would be nice, but also jQuery is fine too.

Answer

James Montagne picture James Montagne · Jan 16, 2012

You can change the pseudo-element based on hover of the parent:

JSFiddle DEMO

#button:before {
    background-color: blue;
    content: "";
    display: block;
    height: 25px;
    width: 25px;
}

#button:hover:before {
    background-color: red;
}

#button {    display: block;
    height: 25px;
    margin: 0 10px;
    padding: 10px;
    text-indent: 20px;
    width: 12%;}

#button:before { background-color: blue;
    content: "";
    display: block;
    height: 25px;
    width: 25px;}

#button:hover:before { background-color: red;}
<div id="button">Button</div>