3

我有这个简单的 CSS:

.cont div {

  margin:10px;
  border:1px solid;
}

.mark {   /* This get ignored? */

 margin:30px;
}

使用此标记:

<div class="cont">
  <div>a</div>
  <div class="mark">b</div>
</div>

我除了 div.mark 之外,margin:30px;但至少在 Chrome 中这是不正确的,因为通用规则.cont div似乎具有更高的优先级。

考虑我不想使用!important有没有其他方法可以解决这个问题?

http://jsfiddle.net/xNVRm/

4

5 回答 5

3

只需通过添加标签名称使您的选择器更具体:

div.mark {
    margin:30px;
}

演示:http: //jsfiddle.net/xNVRm/1/

.cont .mark如果您想避免使用标签名称,也可以使用。

于 2013-01-15T20:43:54.743 回答
3

为了避免使用important你需要使你的css选择器更具体。您可以使用.cont div.mark. 它比 div.mark 更具体。

于 2013-01-15T20:44:18.970 回答
2

“.cont div”声明覆盖了“.mark”声明,因为它实际上更具体。CSS 使用一种点系统来确定适用哪些规则。在您的情况下,“.cont div”指定了一个类和其中的一个元素,而“.mark”只指定了一个类。

有关所有符合标准的浏览器应使用的确切规则,请参阅此链接:http ://www.w3.org/TR/CSS21/cascade.html#specificity

在您的情况下,您可以通过在第二个声明中使用“.cont .mark”来解决此问题。

于 2013-01-15T20:51:36.957 回答
1

Looking over this again, I see I wasn't understanding what you were trying to do. I think I see now.

You are is saying - ANY div inside of anything with class .cont will have 10px margin. It's more specific then .mark. .mark is 30px - BUT it's a div that is inside of .cont - so it's 10px. It reads right to left - that is a good way to think about it and check specificity.

I have come to think of things with a more object oriented approach. What do you think about this approach?


HTML

<div class="container section01">
  <div class="block a">a</div>
  <div class="block b">b</div>
</div>


CSS

.container {
    width: 100%;
    float: left;
    border: 1px solid red;
}

.container .block {
    /* you can style these site wide */
}

.section01 .block {
    border:1px solid black;
    padding:10px;
    margin-bottom: 1em;
}

.section01 .block:last-of-type {
    margin-bottom: 0;
}

.section01 .a {
    background-color: red;
}

.section01 .b {
    background-color: lightblue;
}

SASS would make this much easier.

a jsFiddle of this example

a CODEPEN of this on a larger scale

于 2013-01-15T21:03:03.993 回答
1

特异性是如何给 CSS 规则排序的关键。尝试查看 HTML Dog 中的这篇文章:

http://www.htmldog.com/guides/cssadvanced/specificity/

您可以div.mark改用,这意味着任何具有标记类的 div 都可以这样做。

于 2013-01-15T20:48:42.967 回答