How to make a child div visible when clicking on its parent div in pure css

I have an html structure, usually a div with a “content class” is displayed to the user, and a div with “content content” is displayed until the user clicks or hover over the “head of the class”.

<div class='head'> <div class='content'> content </div> <!- visible --> <div class='tip'> tip </div> <!- invisible --> </div> 

Of course, I can use the code to show the class hint when I click on the parent element. However, I'm just wondering if this is possible with pure css.

I find css technique on web page

 .to-be-changed { color: black; } input[type=checkbox]:checked ~ .to-be-changed { color: red; } 

the demo works, but it works with the input element and check event how to do it when it comes to the div element

I also tried this

 .head.hover ~ .tip { color: red; } .tip { color: black; } 

but for some reason does not work

+4
source share
1 answer

The reason your CSS is not working is due to two small errors.

First, .head.hover defines two class selectors .head and .hover , while you really want :hover user action pseudo class.

Secondly, .head.hover ~ .tip uses ~ common sibling combinator, which will only apply to the .head.hover element preceded by the .tip element, i.e. Elements must "share the same parent element in the document tree." You can use either the offspring compiler or the child combinator to target the .tip child. I used the latter in the following example:

Thus, fixing these issues leads to CSS:

 .head:hover > .tip { color: red; } .tip { color: black; } 

which changes the color of the tip on hover.

Regarding CSS click events, there are many different ways to achieve CSS click events, as described in the blog you are attached to.

One that might work for your situation is an approach :focus , which relies on an element with tabindex .

HTML

 <div class="head" tabindex="1"> <div class="content"> content </div> <div class="tip"> tip </div> </div> 

CSS

 .head .tip { display:none; } .head:focus .tip { display:block; } 

See demo

+4
source

All Articles