在div的列表中按类名选择第一个元素(仅CSS)

时间:2019-06-19 09:39:55

标签: css pseudo-element

我只希望在两种情况下都只能在具有相同HTML元素的列表中使用CSS(在这种情况下为div)来定位“ lorem”。因此,当我从列表中删除ID时,它仍应仅使用类'items__item'设置第一个元素的样式。有人有主意吗?

.items {
  display: flex;
  flex-direction: row;
  margin: 10px;
}
.items > div {
  padding: 0 5px;
}

.items__item:first-child {
  color: green;
}

.items__item:first-of-type {
  color: green;
}

.items__item:nth-of-type(2) {
  color: red;
}
<div class="items">
  <div class="id">23432</div>
  <div class="items__item">lorem</div>
  <div class="items__item">ipsum</div>
  <div class="divider">|</div>
  <div class="items__item">dolor</div>
</div>

<div class="items">
  <div class="items__item">lorem</div>
  <div class="items__item">ipsum</div>
  <div class="divider">|</div>
  <div class="items__item">dolor</div>
</div>

1 个答案:

答案 0 :(得分:0)

.items {
  display: flex;
  flex-direction: row;
  margin: 10px;
}
.items > div {
  padding: 0 5px;
}

.items div.items__item ~ div.items__item  {
  color: black;
}

.items div.items__item {
  color: red;
}
<div class="items">
  <div class="id">23432</div>
  <div class="items__item">lorem</div>
  <div class="items__item">ipsum</div>
  <div class="divider">|</div>
  <div class="items__item">dolor</div>
</div>

<div class="items">
  <div class="items__item">lorem</div>
  <div class="items__item">ipsum</div>
  <div class="divider">|</div>
  <div class="items__item">dolor</div>
</div>

现在,如果您删除具有类ID的元素,它将起作用。