css - 我将如何使用 CSS 定位此 div?

标签 css css-selectors

在下面的代码中,我如何使用 CSS 定位第二个 div.b

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

最佳答案

在此特定实例中,您可以使用 adjacent sibling combinator, + .

EXAMPLE HERE

.b + .b {
   color:red;
}

以上假定不超过两个相邻的 .b 元素。如果不是这种情况,general sibling combinator, ~,假设仍然只有两个 .b 元素会更有用。

EXAMPLE HERE

.b ~ .b {
    color:red;
}

作为替代方案,您还可以使用以下内容,它可以处理多个 .b 元素,无论位置如何。最初,使用 .b ~ .b 设置第二个目标元素的样式。然后,您需要使用 .b ~ .b ~ .b 来重置第二个 .b 元素之后的 .b 元素的样式.

EXAMPLE HERE

.b ~ .b {
    color:red;
}
.b ~ .b ~ .b {
    color:initial;
}

这在理论上应该适用于所有情况,例如:

<div class="a">1a</div>
<div class="a">2a</div>
<div class="a">3a</div>
<div class="b">1b</div>
<div class="a">4a</div>
<div class="b">2b</div> <!-- This would be styled red.. -->
<div class="b">3b</div>

还值得注意的是,值 initial在 IE 中不受支持。因此,您可以使用 color:#000reset the color back to the defaults .或者,继承 would work too .

作为一个更实际的例子,你可以使用这样的东西:

EAXMPLE HERE

.b ~ .b {
    width:200px;
    background:blue;
    color:#fff;
}
.b ~ .b ~ .b {
    width:auto;
    background:transparent;
    color:#000;
}

关于css - 我将如何使用 CSS 定位此 div?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22239494/

相关文章:

html - @font-face 在 Firefox 中不合作

受 float div 影响的 jQuery 标题栏高度

jquery - 如何将鼠标悬停在 div 框上并使其第一个子项出现?

javascript - 滚动显示 'no elements found' ?

css - 如何在 HTML 中制作垂直旋转的链接?

javascript - Safari 错误 :first-child doesn't update display:block when items are removed with JS

javascript - 选择未包含在特定元素中的所有元素

python - Xpath 获取带有子标签的父标签

html - Bootstrap Accordion 超出了 div 的范围

java - Selenium WebDriver -- 获取 <span> 文本