html - 如何在 css/scss 中从 child 定位 parent 的 sibling ?

标签 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/

上一篇:javascript - 禁用对数据表中卡住列的重新排序

下一篇:html - "left"标签有效,但顶部仅在我将其设置为 px 时有效,而在我设置为 % 时无效

相关文章:

javascript - 圆 Angular 三 Angular 形(菜单按钮切换)

html - div 中的图像在图像下方有额外的空间

python - Django Compressor 编译 SASS 时出错(--scss 无效选项)

javascript - 轮播 - 无法定位中心图像

javascript - 在 HTML 选择中复制数据(选项)

javascript - polymer 中可调整大小的元素

html - Representative.replace()在数组列表Grails 2.3.8上不起作用

php - Wordpress 中超链接的奇怪链接错误

css - 在SASS中为不同的类添加一个类名

html - 渐变边框和文本在 Safari 和 iPhone 设备上不起作用