【问题标题】:Target elements with multiple classes, within one rule在一个规则中,目标元素具有多个类
【发布时间】:2011-07-08 23:16:21
【问题描述】:

我有一些 HTML 包含多个类的元素,我需要在一个规则中分配它们,以便相同的类在不同的容器中可能不同。假设我的 CSS 中有这个:

.border-blue {
    border: 1px solid blue;
}
.background {
    background: url(bg.gif);
}

然后我的 HTML 中有这个:

<div class='border-blue background'>Lorum Crap No-one Cares About Ipsum</div>

我可以在一个规则中定位这些吗?例如,像这样,我知道这是行不通的:

.border-blue, .background {
    border: 1px solid blue;
    background: url(bg.gif);
}

【问题讨论】:

    标签: css class target


    【解决方案1】:

    .border-blue.background { ... } 用于具有多个类的一项。
    .border-blue, .background { ... } 用于具有自己的类的多个项。
    .border-blue .background { ... } 用于其中 '.background' 是 ' 的子项的一项.border-blue'。

    请参阅Chris' answer 以获得更详尽的说明。

    【讨论】:

    • 谢谢!我不知道这是否可能,所以我在这里询问。
    • 这个解决方案对我不起作用(或不再起作用......)。
    • 你需要用逗号分隔类,正如克里斯的回答所告诉的那样
    • .border-blue .background { ... } 是孩子是什么意思?我试过这个,这不起作用
    【解决方案2】:

    以防万一有人像我一样偶然发现但没有意识到,以上两种变体适用于不同的用例。

    以下内容:

    .blue-border, .background {
        border: 1px solid #00f;
        background: #fff;
    }
    

    适用于当您想要为具有蓝色边框或背景类的元素添加样式时,例如:

    <div class="blue-border">Hello</div>
    <div class="background">World</div>
    <div class="blue-border background">!</div>
    

    都将应用蓝色边框和白色背景。

    但是,接受的答案是不同的。

    .blue-border.background {
        border: 1px solid #00f;
        background: #fff;
    }
    

    这会将样式应用于具有两个类的元素,因此在此示例中,只有具有两个类的 &lt;div&gt; 才能应用样式(在正确解释 CSS 的浏览器中):

    <div class="blue-border">Hello</div>
    <div class="background">World</div>
    <div class="blue-border background">!</div>
    

    所以基本上这样想,逗号分隔适用于具有一个类或另一个类的元素,点分隔适用于具有一个类和另一个类的元素。

    【讨论】:

    • 这是一个非常有用的答案,我几乎没有阅读。干杯!
    • 小心点。 .blue-border.background中没有空格
    • think of it as AND and OR :很好的建议。我可能会补充一点,.x .y 可以被认为是y &amp;&amp; ancestors.has(x)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多