Charlie-Greenman
Charlie-Greenman

Reputation: 1669

Why does the css element > element work as unexpected in the following instance

So i decided to nest three divs as follows for experimental purposes

<div> 
  <div> 
    <div> 
    </div>
  </div>
</div>

I then went ahead and decided to target the inner divs as follows using css:

div {
  border: 1px solid black;
  padding: 40px;
  background: white;
}

div > div:hover { 
  box-shadow: 0 0 0 40px white;
}

div > div:hover{
  box-shadow: 0 0 0 80px white;
}

What I expected to happen, is either for the page to break, or for it to select all of the divs at once. However, oddly enough it is targeting the divs one by one, propagating if you will.

div {
  border: 1px solid black;
  padding: 40px;
  background: white;
}

div > div:hover { 
    box-shadow: 0 0 0 40px white;
}

div > div:hover{
    box-shadow: 0 0 0 80px white;
}
<div>
    <div> 
        <div>
        </div>
    </div>
</div>     

Upvotes: 2

Views: 62

Answers (2)

Jeff jarrett
Jeff jarrett

Reputation: 11

The code is working perfect.In css the last div selector will of div element will be considered.

If you want to access each div either you can use id or you can use parent-child like:

div:nth-child(2)
{
}     

Upvotes: 0

Josh Beam
Josh Beam

Reputation: 19792

Actually only this last class is being used (CSS in general uses the last-defined class properties, with some exceptions, such as ID selectors, !important declarations, etc.):

div > div:hover {
  box-shadow: 0 0 0 80px white;
}

You have three div elements nested. So the second div in the hierarchy obeys the rule (it is a direct descendant of the first div), and the third div in the hierarchy also obeys the rule... It is a direct descendant of the second div in the hierarchy.

Nothing is broken or unexpected about it. The direct descendant operator > is working exactly as it should in your case.

Upvotes: 7

Related Questions