# 如何实现容器中子元素三个三列布局,子元素两个则两列布局
更多描述
及容器中有三个及以上元素,则三列布局 容器只有两个元素,两列布局平分 容器只有一个元素,一列布局全占
Issue
欢迎在 Gtihub Issue 中回答此问题: Issue 486 (opens new window)
Author
css 布局阔以使用flex
,grid
.
关健在于如何判断有多少元素。我们只需要判断有 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
反过来,前 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;
}