【问题标题】:CSS: Can I select every type of element that are not within a specific class?CSS:我可以选择不在特定类中的每种类型的元素吗?
【发布时间】:2013-10-03 23:32:30
【问题描述】:

假设我得到了这个页面:

<body>
    <h1>Hello!</h1>
    <div class="wrapper">
        <div class="anotherclass">
            <h1>Another heading 1</h1>
        </div>
        <div class="yetanotherclass">
            <h1>Yet another heading 1</h1>
        </div>
    </div>
    <h1>Good bye!</h1>
    <div class="class">
        <h1>Good bye. And this time I mean it.</h1>
    </div>
</body>

我想选择所有不在wrapper 类中的H1 元素。我怎样才能用 CSS 做到这一点? 我不想要这样的“解决方案”

body h1, body .class h1 {style definitions}

我更喜欢这种:

h1:not(.wrapper > h1) {style definitions}

有什么办法吗?

【问题讨论】:

    标签: css css-selectors


    【解决方案1】:

    如果你做了这样的事情会怎样:

    h1 { /* rules for everything without the class */ }
    h1.class { /* rules for everything with the class */ }
    

    h1.class 中,您将覆盖您在h1 规则中定义的所有内容。

    这是一个例子:

    <html>
        <head>
            <style type="text/css">
                    div { color:#00f; }
                    div.foo { color:#f00; }
            </style>
        </head>
        <body>
            <div class="foo">foo</div>
            <div>bar</div>
            <div>baz</div>
        </body>
    </html>
    

    在这个例子中,我有效地定位了所有没有foo 类的divs

    【讨论】:

    • 这在我目前的解决方案中是不可能的。我无法更改 HTML 代码,因为它加载了来自外部服务器的 Javascript,因此我无法在标题上设置类。
    • 我编辑了答案以删除示例中的类。您根本不需要更改 HTML,因为第一条规则将为 all 元素设置样式,而第二条规则仅适用于您要排除的类。
    【解决方案2】:

    你不能用 css 做你要求的事情。围绕 css 的整个想法是级联,而您想要做的是反对级联的流程。

    顺应潮流做常规css:

    h1 {style definitions}
    .wrapper h1 {style definitions}
    

    【讨论】:

      【解决方案3】:

      您可以使用通用选择器 * 应用全局样式,然后应用嵌套的通用选择器: .wrapper * 撤消您最初应用的样式

      * {font-weight:bold; border:thin solid red;}
      
      .wrapper * {font-weight:normal; border: 0px solid white;}
      

      【讨论】:

      • 问题是我将使用这个选择器作为 javascript 的输入,它可以理解 css 选择器 - 但不是那些嵌套的变体。一定是“单排”的东西
      • “有点理解 css 选择器”建议使用 jQuery。您当然可以在 jQuery 中添加目标父类等。
      • 这实际上是我正在结合富文本编辑器执行的 sIFR 实现。富文本编辑器位于包含 h2 和 h3 类型元素的特定 div 中,对于那些我不希望 sIFR 替换文本但在该类型的所有其他出现的元素上的元素。
      • 使用通用选择器作为键选择器是不好的做法;它正在降低性能。
      猜你喜欢
      • 2018-09-16
      • 2012-02-24
      • 1970-01-01
      • 2023-03-29
      • 2017-05-21
      • 2021-10-01
      • 2021-09-11
      • 1970-01-01
      相关资源
      最近更新 更多