2016-03-07 55 views
0

以下代码当我使用id属性作为父母margin-bottom未得到应用,而当我将其用作父母class时,它起作用,是否覆盖或优先事项?当父母身份为ID时,CSS规则不起作用

.prof { 
    margin: 10px 0 0; 
    .parent & { 
    margin: 15px 0 0; 
    position: relative; 
    } 

.js-prof, 
.js-prof-layout { 
    .prof { 
    margin-bottom: 10px; 
    } 
} 

margin-bottom: 10px不与父母工作作为id

.prof { 
    margin: 10px 0 0; 
    #parent & { 
    margin: 15px 0 0; 
    position: relative; 
    } 

.js-prof, 
.js-prof-layout { 
    .prof { 
    margin-bottom: 10px; 
    } 
} 

请注意,这是完全一样的页面

margin-bottom: 10px当父被用作class工作但唯一的区别是添加父母作为id不工作,同时将其添加为class作品!任何解释?谢谢

+2

你将需要演示这个。 –

+1

您的CSS规则正按预期工作 - 它们不会被破坏。你应该阅读[CSS特定性](https://css-tricks.com/specifics-on-css-specificity/) – chazsolo

+0

我们需要看到你的HTML也使用这些类,否则我们不能帮你。 – TylerH

回答

1

假设缺少}只是一个错字,它确实是一个特定的问题,因为你认为。

翻译的CSS外观的有关部分如下

.parent .prof { 
    margin: 15px 0 0; 
    position: relative; 
} 
.js-prof-layout .prof { 
    margin-bottom: 10px; 
} 

在这里你可以看到,对于prof元素顶部规则有两类的选择,而底部治也有两类。所以底层规则具有相同的特性,因此覆盖顶层规则(如后面的样式表中所示)。

但是,如果将.parent替换为#parent,则顶层规则具有一个ID和一个类,因此具有更高的特异性,所以底层规则不会覆盖它。

一种可能的解决方案是在最高规则中不分配margin-bottom,即只写margin-top而不是margin速记。
或者用更完整的选择器编写新的样式规则,例如#parent .js-prof-layout .prof。 (这个取决于HTML的结构。)