Sushil
Sushil

Reputation: 390

How to make only own child visible on hover, using only css

I am working with a list of items, and when each item is hovered, I need to show an element inside that item. Is there a way to achieve this using only css?

Update: Using direct descendent operator (>) is a solution, but element to show/hide may be deeper down

HTML

<div class="list-of-things">
  <div class="each-item">
    ...
    // deeper down in the tree
    <div class="invisible-element">
      Show me only when *my* parent is hovered
    </div>
    ...
  </div>
  <div class="each-item">
    ...
    // deeper down in the tree
    <div class="invisible-element">
      Show me only when *my* parent is hovered
    </div>
    ...
  </div>
</div>

CSS

.each-item:hover {
  // ???
  // (only-this) .invisible-element {
  //   visibility: visible;
  // }
}

Thanks!

Upvotes: 1

Views: 151

Answers (2)

Real Quick
Real Quick

Reputation: 2800

Use the > css selector. In your case it would be:

element > element

div > p

Selects all p elements where the parent is a div element

.invisible-element {
  visibility: hidden;
}
.each-item:hover > .invisible-element {
  visibility: visible;
}
<div class="list-of-things">
  <div class="each-item">
    <div class="invisible-element">
      Show me only when *my* parent is hovered
    </div>
  </div>
  <div class="each-item">
    <div class="invisible-element">
      Show me only when *my* parent is hovered
    </div>
  </div>
</div>

Upvotes: 1

Boris Grigorov
Boris Grigorov

Reputation: 408

Try this:

#parent .hidden-child{
    visibility: hidden;
}

#parent:hover .hidden-child{
    visibility: visible;
}

Upvotes: 3

Related Questions