【css】——根据div个数显示不同的样式

时间:2024-03-09 08:56:25

这里记录面试融众集团的一道题

Q:说可能有1~3个item显示在同一行,而item的个数不一定,如果1个,那这个item占宽100%,2个时每一个50%,3个时每一个33%,用纯CSS实现。

A:先贴答案。

  <style>
    section {
      width: 100%;
    }
    .item {
      float: left;
      width: 100%;
      background: #ccc;
      margin: 4px 0;
      text-align: center;
    }
    div:first-child:nth-last-child(2),
    div:first-child:nth-last-child(2) ~ div {
      width: 50%;
    }
    div:first-child:nth-last-child(3),
    div:first-child:nth-last-child(3) ~ div {
      width: 33.33%;
    }
  </style>

  <section>
    <div class="item">item1</div>
    <div class="item">item2</div>
    <div class="item">item3</div>
  </section>

解释:主要考量对CSS3选择器的熟悉程度, div:first-child:nth-last-child(2) 指选择具有相同父元素的第一个div,同是这个div也是倒数第二个元素,这就说明存在两个具有相同父元素的div。~选择相邻元素。

参考:
:nth-child和:nth-of-type之间的差异