仅当第一个元素具有其他同级对象时才定位

仅当第一个元素具有其他同级对象时才定位

本文介绍了仅当第一个元素具有其他同级对象时才定位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Without adding any classes (or touching the HTML) is there a way to target the first element inside a div ONLY if there is a second element in that div? Below is my 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,那么我希望它们彼此相邻浮动.

A few context to this for a better picture ... I want to center the .content if it's the only .content inside .grid. But if there are two .content divs, then I want them to float next to each other.

注意:

我已经知道我可以通过

.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)将是您的选择器.

这篇关于仅当第一个元素具有其他同级对象时才定位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 01:22