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

查看:510
本文介绍了我可以编写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>

我想编写一个选择器来选择所有不具有可打印"类的元素,在这种情况下,这些元素是 nav a 元素

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的实际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()),则最好为 do 具有可打印"类的元素创建样式规则.即使您对实际标记说了什么,即使这样做还是不可行,则可能必须围绕该限制来进行标记.

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.

请记住,根据您在此规则中设置的属性,其中某些属性可能被 are .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天全站免登陆