如果 DIV 没有特定的同级,则 CSS 定位

Mat*_*ith 2 html css

我正在使用第三方应用程序生成的标记,因此我对其进行品牌化并遇到了我无法解决的情况。大多数时候,HTML<div>容器中会有两个<div>具有相同类名 的s formCol。总有一个clear兄弟姐妹:

<div class="formRow">
    <div class="formCol">Two Divs</div>
    <div class="formCol">With the Same Class</div>
    <div class="clear"></div>
</div>
Run Code Online (Sandbox Code Playgroud)

.formCol有时容器中只有一个。我希望能够在formRow只有一个时定位formCol,但因为它仍然是我无法使用clear的兄弟姐妹。:only-of-type:only-child

<div class="formRow">
    <div class="formCol">One Div</div>
    <div class="clear"></div>
</div>
Run Code Online (Sandbox Code Playgroud)

formRow当其中只有一个时我该如何定位formCol

Sal*_*n A 6

假设它.clear始终存在,您可以组合两个nth-伪类:

/* it is the first child and the second last child at the same time */
:nth-child(1):nth-last-child(2) {
  background-color: red;
}
Run Code Online (Sandbox Code Playgroud)
<div class="formRow">
  <div class="formCol">Two Divs</div>
  <div class="formCol">With the Same Class</div>
  <div class="clear"></div>
</div>
<hr>
<div class="formRow">
  <div class="formCol">One Div</div>
  <div class="clear"></div>
</div>
Run Code Online (Sandbox Code Playgroud)

如果您只针对最新版本的浏览器,您可以使用以下新语法:nth-child

/* it is the first .formCol and the last .formCol at the same time */
:nth-child(1 of .formCol):nth-last-child(1 of .formCol) {
  background-color: red;
}
Run Code Online (Sandbox Code Playgroud)
<div class="formRow">
  <div class="formCol">Two Divs</div>
  <div class="formCol">With the Same Class</div>
  <div class="clear"></div>
</div>
<hr>
<div class="formRow">
  <div class="formCol">One Div</div>
  <div class="clear"></div>
</div>
Run Code Online (Sandbox Code Playgroud)

或者:has

/* it is the first .formCol and next sibling is .clear */
.formCol:first-child:has(+ .clear) {
  background-color: red;
}
Run Code Online (Sandbox Code Playgroud)
<div class="formRow">
  <div class="formCol">Two Divs</div>
  <div class="formCol">With the Same Class</div>
  <div class="clear"></div>
</div>
<hr>
<div class="formRow">
  <div class="formCol">One Div</div>
  <div class="clear"></div>
</div>
Run Code Online (Sandbox Code Playgroud)