CSS同级选择器 [英] CSS Sibling Selector

查看:141
本文介绍了CSS同级选择器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是html代码:

<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>

以下是CSS代码:

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

我正在尝试使用input [type = radio]创建CSS单击.我的问题是兄弟姐妹选择器不起作用.

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?

推荐答案

您正在尝试执行同级选择器无法执行的操作.您将无法设置#link1-content的样式,因为它与#link1:checked不在同一父级. 正如@sirko所说,这应该使用Javascript/JQuery完成(请参见下面的代码段).

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).

来源 子级和同级选择器-CSS技巧

请注意,在通用同级选择器和相邻同级选择器中,逻辑都发生在同一父元素内.

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

一个非常简单的jQuery解决方案:

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

Codepen示例

这篇关于CSS同级选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆