我可以写一个CSS选择器选择元素没有某个类吗? [英] Can I write a CSS selector selecting elements NOT having a certain class?

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

我想写一个选择器,选择所有没有printable类的元素

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 */
}

需要更好的浏览器支持(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 未被继承,请在上设置 display:none :not .printable)将阻止它及其所有后代显示,因为它会完全从布局中删除元素及其子树。你可以通过使用 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天全站免登陆