css - 仅当第一个元素有其他兄弟时才将其作为目标

标签 css css-selectors

在不添加任何类(或接触 HTML)的情况下,只有当 div 中有第二个元素时,是否有一种方法可以将 div 中的第一个元素作为目标?以下是我的 HTML:

<div class="grid">
    <div class="content">I WANT TO APPLY CSS TO THIS</div>
    <div class="content">But only if there is 2nd .content element in the same parent element</div>
</div>
<div class="grid">
    <div class="content">Don't apply here</div>
</div>
<div class="grid">
    <div class="content">Don't apply here</div>
</div>
<div class="grid">
    <div class="content">I WANT TO APPLY CSS TO THIS</div>
    <div class="content">But only if there is 2nd .content element in the same parent element</div>
</div>

一些上下文以获得更好的画面...我想将 .content 居中,如果它是 .grid 中唯一的 .content。但是如果有两个 .content div,那么我希望它们彼此相邻 float 。

注意:

我已经知道我可以通过

定位第二个 .content
.grid .content:nth-child(2) { ... }

最佳答案

.grid > .content:first-child:not(:only-child) {
    color: blue;
}
<div class="grid">
    <div class="content">I WANT TO APPLY CSS TO THIS</div>
    <div class="content">But only if there is 2nd .content element in the same parent element</div>
</div>
<div class="grid">
    <div class="content">Don't apply here</div>
</div>
<div class="grid">
    <div class="content">Don't apply here</div>
</div>
<div class="grid">
    <div class="content">I WANT TO APPLY CSS TO THIS</div>
    <div class="content">But only if there is 2nd .content element in the same parent element</div>
</div>

:first-child:not(:only-child) 将是您的选择器。

关于css - 仅当第一个元素有其他兄弟时才将其作为目标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34623991/

相关文章:

javascript - 光滑的 slider : adding space in between images shown

css: element.class.class - 这是什么意思?

html - 将样式应用于除第一个之外的任何子元素的选择器

html - 在唯一的表行上采用最后一个子级而不是第一个子级

html - img 上的 href 链接

javascript - 通过javascript设置CSS li计数器值

多个类名的 YUI 3 选择器

css - 继承多个nth-child时重置nth-child "clear: both"

css - ASP.Net 文本框和输入按钮未使用 CSS 在 FF 中对齐

html - 包含内容的 div 与其他 div 重叠