【问题标题】:Style an element only when there is no h1 sibling element仅当没有 h1 同级元素时才为元素设置样式
【发布时间】:2023-03-14 11:37:01
【问题描述】:

我的页面上有两组标记:

<div class="row">
    <div>Some random div(s)</div>
    <table></table>
</div>

<div class="row">
    <div>Some random div(s)</div>
    <h1>Table Title</h1>
    <table></table>
</div>

div.row 中没有h1 时,我想将margin-top 和其他一些CSS 自定义应用到div.row &gt; table。 例如,在上面的标记中,第一个 table 会被设置样式,但第二个不会。

我找不到为该组条件设置规则的便捷方法。我对 SASS 很陌生,不想将特定类添加到 table 元素。

您对如何实现这一目标有什么建议吗?

【问题讨论】:

  • h1 总是直接出现在table 之前吗?
  • 当有h1时是

标签: css sass


【解决方案1】:

SASS 最终会编译成 CSS,根据 CSS 规则,这样的选择器不可能实现。您必须通过脚本(javascript、jQuery)来完成。对此有很多疑问。检查这些参考:

Apply CSS styles to an element depending on its child elements

CSS selector for “foo that contains bar”?

Is there a CSS parent selector?

最后,检查this link 的原因为什么我们没有父选择器选项。

【讨论】:

    【解决方案2】:

    当您希望设置 table 的样式时,它总是出现在 相邻的 h1 元素之后,这可以在 CSS 中通过结合使用 :not() 和 next-sibling (@ 987654324@) 选择器。

    .row > :not(h1) + table
    

    该规则将匹配任何table 元素直接在一个元素之前不是h1类为 .row 的元素的直接子元素。

    .row > :not(h1) + table {
      border: 1px solid blue;
      margin-top: 10px;
    }
    <div class="row">
      <div>Some random div(s)</div>
      <table>
        <tr>
          <td>This will match the rule</td>
        </tr>
      </table>
    </div>
    <div class="row">
      <div>Some random div(s)</div>
      <h1>Table Title</h1>
      <table>
        <tr>
          <td>This will not match the rule</td>
        </tr>
      </table>
    </div>

    【讨论】:

    • 谢谢,它按预期完成了工作。没想到:not() 选择器。
    • 没问题,很高兴我能帮上忙。
    猜你喜欢
    • 2022-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-13
    • 2012-10-21
    • 2011-09-04
    相关资源
    最近更新 更多