Roy
Roy

Reputation: 987

Setting a revealing onhover behaviour for multiple elements-pairs with only CSS - how come this works?

Maybe it's a strange question since I don't wanna know 'how' but 'why', but I think the answer might be valuable for those who wish to understand the way css works better.

I'm trying to make each div on my page reveal an 'x' div which will allow the user to close that div. There are several dynamically created divs.

I have this (dynamic) html:

<div class="box">
  <div class="x">X</div>
</div>
<div class="box">
  <div class="x">X</div>
</div>

[the number of 'box' divs varies]

And this css:

.x {
  visibility: hidden;
}
.box:hover .x {
  visibility: visible;
}

I really didn't think this could work but somehow it does:

jsFiddle

But how does this simple css code 'knows' which x div should be revealed, where there are no ids to distinct the 'box' divs nor the 'x' divs?

Upvotes: 0

Views: 36

Answers (1)

Rick Kuipers
Rick Kuipers

Reputation: 6607

Because it looks for the descendent .x So when you hover over box 2 it applies the :hover and according to the css rule the .x that's inside the .box with the :hover should be visible.

Wouldn't really know how to explain it differently :P

Upvotes: 2

Related Questions