I am new to html and css. I'd like to create an function that given a number k between 1 to 9, there will be k divs displayed inside the container div. However, the arrangement of blocks varies as k differs. For example, for k=4, the arrangement will be 2x2, while for k=6, the arrangement will be 3x2. All arrangement can be seen in the below picture. picture Is there any way I can adjust the arrangement based on the number of divs? I guess I should use flexbox for css but I somehow could not find the correct configuration of the container.

推荐答案

下面是一个使用display: grid;:has()的css伪类的纯css解决方案.使用:has(),我们可以根据元素的子计数将样式应用到元素:

#container:has(div:nth-child(3)) {
  grid-template-columns: 1fr 1fr;
  grid-template-rows: 1fr 1fr;
}

仅当包含至少3个子元素时,上述样式才会应用于包含id="container"的元素.

JS Fiddle

(仅用于将div添加到容器中用于演示)

Sources:

解释如何根据元素的子元素设置样式的文章计数:https://www.matuzo.at/blog/2022/counting-children/

:has()伪类css:https://developer.mozilla.org/en-US/docs/Web/CSS/:has

Javascript相关问答推荐

React 17与React 18中的不同setState行为

如何粗体匹配的字母时输入搜索框使用javascript?

colored颜色 检测JS,平均图像 colored颜色 检测JS

如何在Javascript中使用Go和检索本地托管Apache Arrow Flight服务器?

如何从调整大小/zoom 的SVG路径定义新的d属性?""

显示图—如何在图例项上添加删除线效果?

这个值总是返回未定义的-Reaction

当使用';字母而不是与';var#39;一起使用时,访问窗口为什么返回未定义的?

本地库中的chartjs-4.4.2和chartjs-plugin-注解

在Reaction中的handleSubmit按钮内,useSelector值仍然为空

如何在Node.js中排除导出的JS文件

使用jQuery find()获取元素的属性

ngOnChanges仅在第二次调用时才触发

postman 预请求中的hmac/sha256内标识-从js示例转换

Cherrio JS返回父div的所有图像SRC

Reaction即使在重新呈现后也会在方法内部保留局部值

AG-GRIDreact 显示布尔值而不是复选框

如何使用puppeteer操作所有选项

我的NavLink活动类在REACT-ROUTER-V6中出现问题

计算对象数组中属性的滚动增量