仅当有两个或更多元素时才使用last-of-type

Cli*_*een 2 html css css-selectors css3

我正在构建一个页面,我不知道页面上会有多少元素.通常有两个,所以我有样式来定位第一个元素和最后一个元素.这很有效,直到只有一个元素,然后它获得最后的元素样式.

有没有办法用CSS来确保是否只有一个元素没有收到第一个或最后一个元素的样式.如果可能的话,我想尽量避免使用JS.

CSS

.content-box
  .item:first-of-type
    // some styles
  .item.last-of-type
    // some styles
Run Code Online (Sandbox Code Playgroud)

Ori*_*iol 8

:not只有当第一个元素不是最后一个元素时,才可以使用伪类来匹配第一个元素,反之亦然:

.item:first-of-type:not(:last-of-type) { /* ... */ }
.item:last-of-type:not(:first-of-type) { /* ... */ }
Run Code Online (Sandbox Code Playgroud)

li:first-of-type:not(:last-of-type) { 
  background: #ff0;
}
li:last-of-type:not(:first-of-type) {
  background: #0f0;
}
Run Code Online (Sandbox Code Playgroud)
<ul>
  <li>First</li>
  <li>Foo</li>
  <li>Bar</li>
  <li>Last</li>
</ul>
<hr />
<ul>
  <li>First-Last</li>
</ul>
Run Code Online (Sandbox Code Playgroud)

或者,你可以用:first-of-type:last-of-type同步:

.item:first-of-type { /* ... */ }
.item:last-of-type { /* ... */ }
.item:first-of-type:last-of-type { /* Unset styles */ }
Run Code Online (Sandbox Code Playgroud)

li:first-of-type { 
  background: #ff0;
}
li:last-of-type {
  background: #0f0;
}
li:first-of-type:last-of-type {
  background: transparent;
}
Run Code Online (Sandbox Code Playgroud)
<ul>
  <li>First</li>
  <li>Foo</li>
  <li>Bar</li>
  <li>Last</li>
</ul>
<hr />
<ul>
  <li>First-Last</li>
</ul>
Run Code Online (Sandbox Code Playgroud)