How to add more css properties into an CSS rule without remove other existing properties

StackOverflow https://stackoverflow.com/questions/8777662

  •  15-04-2021
  •  | 
  •  

Question

Let say I have some code
HTML code:

<ul>
    <li>
        <h1>Title 1</h1>
        <p>Text 1</p>
    </li>
    <li>
        <h1>Title 2</h1>
        <p>Text 2</p>
    </li>
</ul>

CSS code:

ul li h1 {
    background: #bada55;
}

Now, when I hover on <li>, I want the text inside turns to red. So I write a jQuery code:

$('li').hover(function(){
    $(this).find('h1').css('color': 'red');
});

The text turns to red, but it removes the <h1> 's background property. So, anyone show me the solution? Thanks

Was it helpful?

Solution

There is CSS rule to hover which works in most modern browsers

ul li:hover h1{ color: red; }

it will not overwrite original rules

OTHER TIPS

There are two ways. One using only css, one uses jquery aswell.

You could create a class in CSS, containing the red color.Then add that class to the hovered h1.

h1.redhover { color: #f00 }

$(this).addClass('redhover')

Or add the following in css:

ul li h1:hover {color: #f00;}

The first would be specific for some h1, and the other one would be for all h1's that are inisde a ul and a li.

Good luck!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top