css - 具有两个类之一但不能同时具有两个类的元素的选择器

标签 css css-selectors

如何选择具有两个类之一但不能同时具有两个类的元素?

我试过了 :not(.class1, .class2):not(.class1):not(.class2)但他们似乎选择了缺少任何一个类的元素。我需要选择没有两个类的元素。

我也试过:not([class='class1 class2']) as this accepted answer states , 但它似乎没有选择任何东西。

这是我想要的示例 -

ul.tabs > li.active:not([class='first last']) {
    background-color: #F00;
}
<ul class="tabs">
    <li class="first">1st</li>
    <li class="active last">2nd</li> <!-- Should be red -->
</ul>

<ul class="tabs">
    <li class="active first last">1st</li> <!-- Should NOT be red -->
</ul>

<li>还有其他我不负责的类(class)。我想知道是否有办法忽略我最后尝试的选择器的其他类。

最佳答案

你想要 :not(.first), :not(.last) 这是 :not(.first.last) 的选择器级别 3 支持的版本(来自 Selectors 4,尚未被所有浏览器以及 jQuery 支持):

ul.tabs > li.active:not(.first), ul.tabs > li.active:not(.last) {
    background-color: #F00;
}
<ul class="tabs">
    <li class="first">1st</li>
    <li class="active last">2nd</li>
</ul>

<ul class="tabs">
    <li class="active first last">1st</li>
</ul>

不过,正如 Rounin 指出的那样,您应该能够只使用 :first-of-type:last-of-type,或者 : first-child:last-child,而不是用“first”和“last”类来膨胀标记(如果这些类表示与伪类相同的东西)。

事实上,如果你切换到那些伪类,你可以通过压缩 :not(:first-of-type), :not(:last-of-type 将你的 CSS 简化为只有一个选择器):not(:only-of-type):

ul.tabs > li.active:not(:only-of-type) {
    background-color: #F00;
}
<ul class="tabs">
    <li>1st</li>
    <li class="active">2nd</li>
</ul>

<ul class="tabs">
    <li class="active">1st</li>
</ul>

关于css - 具有两个类之一但不能同时具有两个类的元素的选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50289786/

相关文章:

javascript - 包括 jquery 移动多页站点中的页眉和页脚

html - 为什么我的 Bootstrap Pills 下拉菜单不起作用?

javascript - 有谁知道如何使用 CSS 和 HTML 创建这样的图像容器?

html - 如何在没有 JS 的情况下为最后一个可见元素添加样式

html - CSS 类选择器与 id 选择器的行为不同

html - CSS - 只选择第一组类

javascript - jQuery 将类数字添加到 x 并重新开始

css - 手机上的 HTML 表格滚动

html - 不同尺寸的 ul 对齐

css - angularJS nth-child 不在 ng 重复中工作