我可以编写一个 CSS 选择器来选择没有特定类或属性的元素吗? [英] Can I write a CSS selector selecting elements NOT having a certain class or attribute?

查看:36
本文介绍了我可以编写一个 CSS 选择器来选择没有特定类或属性的元素吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个 CSS 选择器规则来选择所有具有特定类的元素.例如,给定以下 HTML:

I would like to write a CSS selector rule that selects all elements that don't have a certain class. For example, given the following HTML:

<html class="printable">
    <body class="printable">
        <h1 class="printable">Example</h1>
        <nav>
            <!-- Some menu links... -->
        </nav>
        <a href="javascript:void(0)" onclick="javascript:self.print()">Print me!</a>
        <p class="printable">
            This page is super interresting and you should print it!
        </p>
    </body>
</html>

我想编写一个选择器来选择所有没有可打印"类的元素,在这种情况下,是 nava 元素.

I would like to write a selector that selects all elements that don't have the "printable" class which, in this case, are the nav and a elements.

这可能吗?

注意:在我想使用它的实际 HTML 中,没有具有可打印"类的元素要多得多(我意识到这是上面例子中的另一种方式).

NOTE: in the actual HTML where I would like to use this, there are going to be a lot more elements that don't have the "printable" class than do (I realize it's the other way around in the above example).

推荐答案

通常,您将类选择器添加到 :not() 伪类,如下所示:

Typically you add a class selector to the :not() pseudo-class like so:

:not(.printable) {
    /* Styles */
}

:not([attribute]) {
    /* Styles */
}

但如果您需要更好的浏览器支持(IE8 及更早版本不支持 :not()),您可能最好为支持 有可打印的"班级.如果尽管您对实际标记说了些什么,这仍然不可行,那么您可能必须围绕该限制来处理标记.

But if you need better browser support (IE8 and older don't support :not()), you're probably better off creating style rules for elements that do have the "printable" class. If even that isn't feasible despite what you say about your actual markup, you may have to work your markup around that limitation.

请记住,根据您在此规则中设置的属性,其中一些属性可能会被 .printable 的后代继承,或者以其他方式继承以某种方式影响他们.例如,虽然 display 不是继承的,但在 :not(.printable) 上设置 display: none 将阻止它及其所有后代从显示中删除,因为它从布局中完全删除了元素及其子树.你通常可以通过使用 visibility: hidden 来解决这个问题,这将允许可见的后代显示,但隐藏的元素仍然会像最初那样影响布局.简而言之,小心点.

Keep in mind that, depending on the properties you're setting in this rule, some of them may either be inherited by descendants that are .printable, or otherwise affect them one way or another. For example, although display is not inherited, setting display: none on a :not(.printable) will prevent it and all of its descendants from displaying, since it removes the element and its subtree from layout completely. You can often get around this by using visibility: hidden instead which will allow visible descendants to show, but the hidden elements will still affect layout as they originally did. In short, just be careful.

这篇关于我可以编写一个 CSS 选择器来选择没有特定类或属性的元素吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆