Search code examples
htmlcssbackground-colormousehover

Invert text color to color of bg on hover


Is there a way to create rule which will allow me to on hover change link's text color to background color and background color to old text color?

Here is the example of code that i don't like (jsfiddle link):

a {
    background-color: white;
    border: 2px solid #dea12c;
    color: #dea12c;
}
a:hover {
    background-color: #dea12c;
    color: white;
}

Suppose i wanna use five, seven or twenty colors! It will be really booring to create a :hover rule for EVERY element, it would be much more easy, fast and elegant to create only one :hover rule for all elements at once. It should look like this:

a.red {
    background-color: white;
    border: 2px solid red;
    color: red;
}
a.blue {
    background-color: white;
    border: 2px solid blue;
    color: blue;
}
...
a:hover {
    background-color: initialBorderColor;
    color: white;
}

It is veeery easy to achieve this with JS but i want only CSS+HTML solution.


Solution

  • Live Demo

    <a>MOVE YOUR CURSOR HERE!</a> 
    
    <a>MOVE YOUR CURSOR HERE!</a>
    

    Style

    a:nth-child(1) {
        background-color: #FFF000;
        border: 2px solid #000FFF;
        color: #000FFF;
    }
    a:nth-child(2) {
        background-color: #0077CC;
        border: 2px solid #FF8833;
        color: #FF8833;
    }
    a:hover {
        -webkit-filter: invert(100%);
        filter: invert(100%);
    }
    

    this tool can generate inverted color pairs : TOOL


    update(because of comments ):

    Demo

    I think there are no way to read anther element style using pure css

    <a class="delete">Delete</a> 
    <a class="create">Create</a>
    <a class="black">Black</a>
    

    style

    .delete{
        background-color: #FFF;
        border: 2px solid #F00;
        color: #F00;    
    }
    .create{
        background-color: #FFF;
        border: 2px solid #0F0;
        color: #0F0;    
    }
    .black{
        background-color: #FFF;
        border: 2px solid #000;
        color: #000;    
    }
    .delete:hover{
        background-color: #F00;
        border: 2px solid #FFF;
        color: #FFF;   
    }
    .create:hover{
        background-color: #0F0;
        border: 2px solid #FFF;
        color: #FFF;    
    }
    .black:hover{
        background-color: #000;
        border: 2px solid #FFF;
        color: #FFF;    
    }