CSS Sibling Selector

2019-09-08 16:08发布

问题:

Here are html codes:

<div class="wrapper">
  <div class="menu-wrap">
    <ul>
     <li>
       <input type="radio" id="link1" />
     </li>
    </ul>
  </div>

  <div class="content-wrap">
    <div id="link1-content"><p>Just a paragraph</p></div>
  </div>
</div>

Here are css codes:

#link1:checked ~ #link1-content { display: none;}

I am trying to create css click with input[type=radio]. My problem is that the sibling selector does not work.

How can I write appropriate sibling selector?

回答1:

You are trying to do something sibling selectors cannot do. You will not be able to style #link1-content because it does not share the same parent as #link1:checked. As @sirko said, this is something that should be accomplished with Javascript/JQuery (see my snippet below).

Source Child and Sibling selectors -- CSS Tricks

Note that in both the general sibling and adjacent sibling selectors the logic takes place within the same parent element.

A very simple jQuery solution:

$('#link1').change(function(){
  $('#link1-content').toggle();
});

Codepen example