相邻的兄弟选择器,具有封闭类的特异性 [英] Adjacent Sibling Selectors with specificity of an enclosing class

查看:124
本文介绍了相邻的兄弟选择器,具有封闭类的特异性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个DOM:

 < div class =a> 
< div class =b>< / div>
< div class =c>< / div>
< / div>

我想有这个css规则:

  .b + .c {margin-left:220px; } 

但仅在类 a p>

我希望这样的东西能工作,但没有运气。

  .a .b + .a .c {} 

有没有人知道这是否可能?

解决方案

改用此选择器:

  .a .b + .c {
margin-left:220px;
}

...或 .a> .b + .c ,如果您希望规则仅应用于 .a 容器的子项,而不是其所有后代。



演示



现在解释部分。如 CSS规格中所定义,每个选择器 + 符号被视为选择器链:


由单个简单选择器组成的选择器匹配任何元素
满足其要求。前面一个简单的选择器和
组合器到一个链强加了额外的匹配约束,所以选择器的
主体总是匹配
的元素的子集最后一个简单选择器。 strong>


现在分析您开始使用的表达式:

  .a .b + .a .c 

spec。这实际上被视为...

 ((。a .b)+ .a).c 

换句话说,选择器已应用...




  • 到所有 .c 元素,... ...

  • ... < $ c> .a 元素作为它们的祖先,... ...

  • ...... .b 元素作为它们的前面的兄弟姐妹,它... ...

  • ..........有 .a 元素作为其祖先。



此选择器将匹配 .c 元素此HTML:

 < div class =a> 
< div class =b>< / div>
< div class =a>
< div class =c>这是匹配的< / div>
< / div>
< / div>

然而,在您的情况下,您不必检查。 c ancestry - 足以检查 .b (它的前面的同级)。如果 .b .a 上的DOM树,它的 sibling 。 )


I have this DOM:

<div class="a">
    <div class="b"></div>
    <div class="c"></div>
</div>

I'd like to have this css rule:

.b + .c { margin-left: 220px; }

BUT only within class a

I was hoping that something like this would have worked , but no luck.

.a .b + .a .c {}

Does anyone know if this is possible ?

解决方案

Use this selector instead:

.a .b + .c {
    margin-left: 220px;
}

... or .a > .b + .c, if you want the rule to be applied only to the children of .a container, rather than to all its descendants.

Demo.

Now for explanation part. As defined in CSS spec, every selector with + symbol is treated as selector chain:

A selector consisting of a single simple selector matches any element satisfying its requirements. Prepending a simple selector and combinator to a chain imposes additional matching constraints, so the subjects of a selector are always a subset of the elements matching the last simple selector.

Now that's analyze the expression you've started with:

.a .b + .a .c

According to spec, this is actually treated as...

((.a .b) + .a) .c

In other words, selector is applied...

  • to all the .c elements, which...
  • ... have .a elements as their ancestors, which...
  • ...... have .b elements as their preceding siblings, which...
  • .......... have .a elements as their ancestors.

This selector will match .c element in this HTML:

<div class="a">
  <div class="b"></div>
  <div class="a">
    <div class="c">This is matched</div>
  </div>
</div>

In your case, however, you won't have to check for .c ancestry - it's enough to check for .b (its preceding sibling) only. If .b has .a up its DOM tree, its sibling sure has it too. )

这篇关于相邻的兄弟选择器,具有封闭类的特异性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆