Html 我可以编写一个 CSS 选择器来选择没有特定类或属性的元素吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9110300/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 22:14:19  来源:igfitidea点击:

Can I write a CSS selector selecting elements NOT having a certain class or attribute?

htmlcsscss-selectors

提问by David Nordvall

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

我想编写一个 CSS 选择器规则来选择所有没有特定类的元素。例如,给定以下 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>

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

我想编写一个选择器来选择所有没有“可打印”类元素,在这种情况下,是导航a元素。

Is this possible?

这可能吗?

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

注意:在我想使用它的实际 HTML 中,将有更多的元素没有“可打印”类(我意识到在上面的例子中是相反的)。

回答by BoltClock

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

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

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

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

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 dohave 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.

但是,如果你需要更好的浏览器的支持(IE8及以上不支持:not()),你可能会更好过该元素创建样式规则有“打印”的类。如果尽管您对实际标记说了些什么,这仍然不可行,则您可能必须围绕该限制处理标记。

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 displayis not inherited, setting display: noneon 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: hiddeninstead which will allow visible descendants to show, but the hidden elements will still affect layout as they originally did. In short, just be careful.

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

回答by Milche Patern

:not([class])

Actually, this will select anything that does not have a css class (class="css-selector") applied to it.

实际上,这将选择没有class="css-selector"应用css 类 ( ) 的任何内容。

I made a jsfiddledemo

我做了一个jsfiddle演示

    h2 {color:#fff}
    :not([class]) {color:red;background-color:blue}
    .fake-class {color:green}
    <h2 class="fake-class">fake-class will be green</h2>
    <h2 class="">empty class SHOULD be white</h2>
    <h2>no class should be red</h2>
    <h2 class="fake-clas2s">fake-class2 SHOULD be white</h2>
    <h2 class="">empty class2 SHOULD be white</h2>
    <h2>no class2 SHOULD be red</h2>

Is this supported?Yes : Caniuse.com (accessed 02 Jan 2020):

这是支持的吗?是:Caniuse.com(2020 年 1 月 2 日访问)

  • Support: 98.74%
  • Partial support: 0.1%
  • Total:98.84%
  • 支持率:98.74%
  • 部分支持:0.1%
  • 总计:98.84%

Funny edit, I was Googling for the opposite of :not. CSS negation?

有趣的编辑,我在谷歌上搜索 :not 的反面。CSS否定?

selector[class]  /* the oposite of :not[]*/

回答by SW4

The :notnegation pseudo class

:not否定伪类

The negation CSS pseudo-class, :not(X), is a functional notation taking a simple selector X as an argument. It matches an element that is not represented by the argument. X must not contain another negation selector.

否定 CSS 伪类 ,:not(X)是一个函数符号,将一个简单的选择器 X 作为参数。它匹配参数未表示的元素。X 不能包含另一个否定选择器。

You can use :notto exclude any subset of matched elements, ordered as you would normal CSS selectors.

您可以使用:not排除匹配元素的任何子集,与普通 CSS 选择器一样排序。



Simple example: excluding by class

简单示例:按类排除

div:not(.class)

div:not(.class)

Would select all divelements without the class .class

将选择div没有类的所有元素.class

div:not(.class) {
  color: red;
}
<div>Make me red!</div>
<div class="class">...but not me...</div>



Complex example: excluding by type / hierarchy

复杂示例:按类型/层次结构排除

:not(div) > div

:not(div) > div

Would select all divelements which arent children of another div

将选择所有div不是另一个子元素的元素div

div {
  color: black
}
:not(div) > div {
  color: red;
}
<div>Make me red!</div>
<div>
  <div>...but not me...</div>
</div>



Complex example: chaining pseudo selectors

复杂示例:链接伪选择器

With the notable exception of not being able to chain/nest :notselectors and pseudo elements, you can use in conjunction with other pseudo selectors.

除了不能链接/嵌套:not选择器和伪元素的显着例外,您可以与其他伪选择器结合使用。

div {
  color: black
}
:not(:nth-child(2)){
  color: red;
}
<div>
  <div>Make me red!</div>
  <div>...but not me...</div>
</div>



Browser Support, etc.

浏览器支持

:notis a CSS3 level selector, the main exception in terms of support is that it is IE9+

:not是一个CSS3 级别选择器,支持方面的主要例外是它是IE9+

The spec also makes an interesting point:

该规范还提出了一个有趣的观点:

the :not()pseudo allows useless selectors to be written. For instance :not(*|*), which represents no element at all, or foo:not(bar), which is equivalent to foobut with a higher specificity.

:not()伪允许写入无用的选择。例如:not(*|*),它根本不代表任何元素,或者 foo:not(bar),它等同于foo但具有更高的特异性。

回答by Eregrith

I think this should work:

我认为这应该有效:

:not(.printable)

From "negative css selector" answer.

来自“否定 css 选择器”的回答

回答by BaneStar007

Just like to contribute that the above answers of :not() can be very effective in angular forms, rather than creating effects or adjusting the view/DOM,

就像贡献 :not() 的上述答案在角度形式中非常有效,而不是创建效果或调整视图/DOM,

input.ng-invalid:not(.ng-pristine) { ... your css here i.e. border-color: red; ...}

Ensures that on loading your page, the input fields will only show the invalid (red borders or backgrounds, etc) if they have data added (i.e. no longer pristine) but are invalid.

确保在加载您的页面时,如果输入字段添加了数据(即不再原始)但无效,则输入字段只会显示无效(红色边框或背景等)。

回答by Hakan

Example

例子

  [class*='section-']:not(.section-name) {
    @include opacity(0.6);
    // Write your css code here
  }

// Opacity 0.6 all "section-" but not "section-name"

// 不透明度 0.6 所有“section-”但不是“section-name”

回答by MelkorNemesis

You can use :not(.class)selector as mentioned before.

您可以使用:not(.class)前面提到的选择器。

If you care about Internet explorer compatibility I recommend you to use http://selectivizr.com/.

如果您关心 Internet Explorer 的兼容性,我建议您使用http://selectivizr.com/

But remember to run it under apache otherwise you won't see the effect.

但是记得在apache下运行,不然看不到效果。

回答by Willem van der Veen

Using the :not()pseudo class:

使用:not()伪类:

For selecting everything but a certain element (or elements). We can use the :not()CSS pseudo class. The :not()pseudo class requires a CSSselector as its argument. The selector will apply the styles to all the elements except for the elements which are specified as an argument.

用于选择除某个元素(或多个元素)之外的所有内容。我们可以使用:not()CSS 伪类。该:not()伪类需要一个CSS选择作为其参数。选择器会将样式应用到所有元素,但指定为参数的元素除外。

Examples:

例子:

/* This query selects All div elements except for   */
div:not(.foo) {
  background-color: red;
}


/* Selects all hovered nav elements inside section element except
   for the nav elements which have the ID foo*/
section nav:hover:not(#foo) {
  background-color: red;
}


/* selects all li elements inside an ul which are not odd */
ul li:not(:nth-child(odd)) { 
  color: red;
}
<div>test</div>
<div class="foo">test</div>

<br>

<section>
  <nav id="foo">test</nav>
  <nav>Hover me!!!</nav>
</section>
<nav></nav>

<br>

<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
</ul>

We can already see the power of this pseudo class, it allows us to conveniently fine tune our selectors by excluding certain elements. Furthermore, this pseudo class increases the specificity of the selector. For example:

我们已经可以看到这个伪类的强大之处,它允许我们通过排除某些元素来方便地微调我们的选择器。此外,这个伪类增加了 selector 的特异性。例如:

/* This selector has a higher specificity than the #foo below */
#foo:not(#bar) {
  color: red;
}

/* This selector is lower in the cascade but is overruled by the style above */
#foo {
  color: green;
}
<div id="foo">"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
  in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</div>

回答by Mihai

If you want a specific class menuto have a specific CSS if missing class logged-in:

如果您希望特定的类菜单在缺少登录类的情况下具有特定的 CSS :

body:not(.logged-in) .menu  {
    display: none
}

回答by HBhering

As others said, you simply put :not(.class). For CSS selectors, I recommend visiting this link, it's been very helpful throughout my journey: https://code.tutsplus.com/tutorials/the-30-css-selectors-you-must-memorize--net-16048

正如其他人所说,您只需输入 :not(.class)。对于 CSS 选择器,我建议访问此链接,它在我的整个旅程中都非常有帮助:https: //code.tutsplus.com/tutorials/the-30-css-selectors-you-must-memorize--net-16048

div:not(.success) {
  color: red;
}

The negation pseudo class is particularly helpful. Let's say I want to select all divs, except for the one which has an id of container. The snippet above will handle that task perfectly.

否定伪类特别有用。假设我想选择所有 div,除了 id 为 container 的那个。上面的代码片段将完美地处理该任务。

Or, if I wanted to select every single element (not advised) except for paragraph tags, we could do:

或者,如果我想选择除段落标签之外的每个元素(不建议),我们可以这样做:

*:not(p) {
  color: green;
}