简体   繁体   中英

CSS hover sub div background color change

I have this Fiddle , and what I am trying to do is when you mouse over each div section, it only changes the background for that section. Is there any way I can do that without having it change the background for everything? When I mouse over .two , the .one:hover gets fired. how can I make it fire .two and not .one when I mouse over .two ?

CSS:

div.one:hover, div.two:hover, div.three:hover{
    background-color: #69aeea;
}

HTML:

<div class="one">
    Text 1
    <div class="two">
        Text 2
        <div class="three">Text 3</div>
        <div class="three">Text 3</div>
        <div class="three">Text 3</div>
    </div>
    <div class="two">
        Text 2
        <div class="three">Text 3</div>
        <div class="three">Text 3</div>
        <div class="three">Text 3</div>
    </div>
</div>

:hover is triggered all the way up to the root parent (typically <body> ), so you can't trigger it only on the child when you have :hover states on the parent.

What you need to do is isolate the parts you actually want to show a hover state, which in this case I accomplished by wrapping the text in a <span> . This will keep the :hover state isolated from the other children of that parent.

<div class="one">
  <span>Text 1</span>
  <div class="two">
    <span>Text 2</span>
    <div class="three"><span>Text 3</span></div>
...

Then target specifically in the CSS: (The > character selects a direct descendent of a parent)

div > span:hover {
  background-color: #69aeea;
}

You can then do different colors based on the level like so:

div.one > span:hover {
  background-color: #69aeea;
}
div.two > span:hover {
  background-color: #ae69ea;
}
div.three > span:hover {
  background-color: #aeea69;
}

DEMO: http://jsfiddle.net/shshaw/8uetm/

Unfortunately, you can't access the parent of an element in CSS. Meaning, that if you hover over a child element, you can't set the background of its parent. You'll have to use javascript to achieve what you're asking.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM