【发布时间】:2017-08-29 13:38:10
【问题描述】:
考虑以下代码:
<h2>
Working example
</h2>
<div class="test">
<button>FirstChild (Yellow)</button>
<button>Middle</button>
<button>Middle</button>
<button>LastChild (Red)</button>
</div>
<div class="test">
<h2>
Not working example - no DIVs
</h2>
<button>FirstChild (Yellow)</button>
<button>Middle</button>
<button>Middle</button>
<button>LastChild (Red)</button>
</div>
<div class="test">
<h2>
Not working example - Divs
</h2>
<div>
<button>FirstChild (Yellow)</button>
</div>
<div>
<button>Middle</button>
</div>
<div>
<button>Middle</button>
</div>
<div>
<button>LastChild (Red)</button>
</div>
</div>
还有以下 CSS:
.test button:first-child {
background: yellow;
}
.test button:last-child {
background: red;
}
.test button:not(:last-child):not(:first-child) {
background: cyan;
}
结果:
如果子按钮元素位于 div 内或中间有另一个元素 (h2),为什么找不到我的 CSS?测试 div 中没有其他按钮元素。
如何让这个 CSS 考虑 3 种给定的情况以及正确的行为(工作示例)?
【问题讨论】:
-
这不起作用,因为它们不是其相同父容器的第一个/最后一个子容器。
-
button:first-child表示:第一个子元素和按钮元素。必须满足这两个要求。 -
感谢@zerkms 的提示。我需要的是“在子树中找到的第一个按钮”或类似的东西......有没有办法做到这一点?
-
@Mendes
first-of-type是你想要的,而不是first-child