<分区>
标签 html css sass css-selectors
<分区>
如何从 child 定位 parent 的 sibling ?我正在尝试制作一个纯 css 汉堡包菜单,我在标签内输入了这个复选框:在内容是 trigram 之前。
在桌面 View 中,ul 列表显示为 block ,而在移动设备上则没有。现在,当 ul 是输入框的直接同级时,显示和隐藏起作用,波浪线选择器起作用。
但是我想做的是取出标签内的 ul 作为它自己的兄弟所以输入是标签剩下的唯一 child 。删除 ul 后,显示和隐藏将不再起作用。
检查输入时如何定位 ul?
HTML:
<nav>
<label class="nav-toggler">
<input type="checkbox" />
</label>
<ul class="nav-links">
<li>link</li>
<li>link</li>
<li>link</li>
</ul>
</nav>
SCSS:
.nav-toggler{
&:before{
content:'\2630';
}
input{
opacity: 0;
width: 0;
height: 0;
&:checked ~ .nav-links{
display: block;
}
}
}
最佳答案
您应该使用带有 id 和 for 属性的标签和输入
寻找父选择器是一种错误的方法,在 CSS 中是不可能的请参阅 Is there a CSS parent selector?
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/label
Associating a
<label>
with an<input>
element offers some major advantages:
The label text is not only visually associated with its corresponding text input; it is programmatically associated with it too. This means that, for example, a screenreader will read out the label when the user is focused on the form input, making it easier for an assistive technology user to understand what data should be entered.
You can click the associated label to focus/activate the input, as well as the input itself. This increased hit area provides an advantage to anyone trying to activate the input, including those using a touch-screen device.
您的 HTML 可以变成
<nav>
<input type="checkbox" id="myId" />
<label class="nav-toggler" for="myId">
</label>
<ul class="nav-links">
<li>link</li>
<li>link</li>
<li>link</li>
</ul>
</nav>
和 (S)CSS 规则
.nav-toggler{
&:before{
content:'\2630';
cursor:pointer;
}
}
input{
opacity: 0;
width: 0;
height: 0;
&:checked ~ .nav-links{
display: block;
}
}
关于html - 如何在 css/scss 中从 child 定位 parent 的 sibling ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56277371/