在一个元素和特异性中使用多个类
只是想知道当您在一个元素上使用多个类(例如 class="foo bar"
),并且这些类的设置如下:
.foo {
margin-right: 10px;
}
.bar {
margin-right: 0px;
}
哪个类将具有特异性?边距是 10px 还是 0px?
Just wondering when you use multiple classes on the one element such as class="foo bar"
and those classes are setup as below:
.foo {
margin-right: 10px;
}
.bar {
margin-right: 0px;
}
Which class will have specificity? Will the margin be 10px or 0px?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
它的工作原理基于 CSS 中的优先级。因此,最近出现的项目将覆盖任何以前的样式。
在这种情况下, CASE 1
class = 'red blue'
将是blue。CASE 2
在本例中,
class = 'blue red'
将是red。工作示例
It works based on precedence within the CSS. Therefore the item to occur most recently will override any previous styles.
CASE 1
class = 'red blue'
would be blue in this instance.CASE 2
class = 'blue red'
would be red in this instance.Working Example
另外,如果您希望定位仅两个类的元素,您可以使用以下语法:
Also, if you wish to target the element who has only both classes, you can use this syntax:
此外,更“具体”的类将覆盖更通用的类:
HTML:
使用以下 CSS:
注意到内部 div 仍然有 25px 的左边距吗?
另外,在提供值后阅读“!important”参数:
查看
In addition, more "specific" class will override a more generic one:
HTML:
With the following CSS:
Notice how the inner div still has 25px margin to the left?
Also, read up on "!important" argument after providing the value:
Check out
单个类名具有相同的权重。在这种情况下,第一个列出的规则将被第二个规则覆盖,因此,该元素将具有
margin-right: 0px;
这是一个 简单示例使用
颜色
而不是边距,因为它更容易可视化。bar
中指定的值将由浏览器选择。A single class name carries the same weight. In such a scenario, the rule that is listed first will be overwritten by the second, and hence, the element will have
margin-right: 0px;
Here is a simple example using
color
instead of margin, because it's easier to visualize. The value specified inbar
will be chosen by the browser.