html - <nav> 和 <button> 是姊妹元素。添加 <nav> 事件类后,如何为 <button> 编写 CSS?

标签 html css

<nav class="">
    <a class="nav-item">1</a>
    <a class="nav-item">2</a>
    <a class="nav-item">3</a>
    <a class="nav-item">3</a>
    <a class="nav-item">4</a>
</nav>

<button class="mobile-button">Button</button>

上面的代码是我的 HTML 模板。如果<nav>中添加“active”类,我想将CSS写入<button>下面,我该如何选择这个?

请不要将按钮放在导航中,我需要这样做。

最佳答案

您可以使用next sibling combinator + 如果按钮紧跟在导航之后:

nav.is-active + .mobile-button {
  /* styles here */
}

或者,如果是更远的 sibling ,您可以使用 ~ subsequent sibling combinator :

nav.is-active ~ .mobile-button {
  /* styles here */
}

使用:has() pseudo-class您还可以引用有活跃 child 的父级,而不是引用目标:

body:has(nav.is-active) .mobile-button {
  /* styles here */
}

或者就像:

:has(nav.is-active) .mobile-button {
  /* styles here */
}

关于html - <nav> 和 <button> 是姊妹元素。添加 <nav> 事件类后,如何为 <button> 编写 CSS?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77586047/

相关文章:

javascript - 在滚动页面时为 div 设置动画

html - Bootstrap 没有正确排列导航悬停的部分

html - 不同对齐绝对位置

javascript - 在用户正在查看的位置弹出 div

html - 如何将文字放在图片之前?

html - 如何在 <symbol> 中使用 <defs> 来 <use> SVG 图像

html - 如何将 profoundgrid "responsive fluid"样式中的 div 推到右侧?

html - CSS(点击)动画不会在 Firefox 中播放多次

html - 使用更漂亮的 css 选择器中的自动换行符

css - 这个子菜单定位可以单独使用 CSS 吗?