首页 > 解决方案 > 基于 DOM 状态的条件 CSS 选择器

问题描述

我有以下要设置样式的代码:

<div class="group">
    <div class="tabs">
        <access type="full">
            <span class="tab">Hello</span>
        </access>
        <span class="tab">World!</span>
    </div>
</div>

此 HTML 将根据路由器防护而更改,但在任何给定时刻,我希望每个选项卡20px之间都有一个边距,并且第一个选项卡的左边距为 0。

我的困惑源于这样一个事实,即 of 的第一个孩子tabs要么是 type 的组件,access要么只是一个 normal span

所以这就是我想要做的:

/* Set every tab to have 20px spacing in between */
.tab {
    margin: 0 0 0 20px;
}

/* Select first child of tabs, whether access component or span and sets margin to 0 */
.tabs > *:nth-child(1) span:first-child,
.tabs span:first-child {
    margin: 0
}

我的理由是,对于第二种风格的第一部分,.tabs > *:nth-child(1) span:first-child,它是:

选择选项卡的第一个子项并选择第一个跨度子项

第二个要阅读:

选择第一个跨度孩子tabs

我怎样才能做到这一点?

标签: htmlcsscss-selectors

解决方案


在我的方法中,我在每个选项卡的右侧添加边距,这样第一个选项卡没有边距,ml:20px但所有选项卡.tabs都被 20px 分隔。

.tabs .tab {
  margin-right: 20px;
}

access {
  margin: 0;
  padding: 0;
}
<div class="group">
  <div class="tabs">
    <access type="full">
      <span class="tab">Hello</span>
    </access>
    <span class="tab">World!</span>
  </div>
</div>


推荐阅读