极客时间返利平台,你可以在上边通过山月的链接购买课程,并添加我的微信 (shanyue94) 领取返现。
山月训练营之面试直通车 服务上线了,从准备简历、八股文准备、项目经历准备、面试、面经、面经解答、主观问题答复、谈薪再到入职的一条龙服务。

# 如何实现容器中子元素三个三列布局,子元素两个则两列布局

更多描述

及容器中有三个及以上元素,则三列布局 容器只有两个元素,两列布局平分 容器只有一个元素,一列布局全占

Issue

欢迎在 Gtihub Issue 中回答此问题: Issue 486 (opens new window)

Author

回答者: 9527YL (opens new window)

代码演示 (opens new window)

css 布局阔以使用flexgrid.

关健在于如何判断有多少元素。我们只需要判断有 1 个,有 2 个的情况,其他都是三列布局

/* 有1个元素 */
.item:nth-last-child(1):first-child {
  flex: 1;
}

.item:nth-last-child(1):first-child ~ .item {
  flex: 1;
}

/* 有2个元素 */
.item:nth-last-child(2):first-child {
  flex: 1;
}

.item:nth-last-child(2):first-child ~ .item {
  flex: 1;
}

Author

回答者: Telanx (opens new window)

反过来,前 3 个设置flex:1,超过 3 个就重置为none

/*前3个flex:1*/
.item:nth-child(-n + 3) {
  flex: 1;
}

/*超过3个则none*/
.item:nth-last-child(4),
.item:nth-last-child(4) ~ .item {
  flex: none;
}
Last Updated: 2/23/2022, 11:56:07 AM