前置知识:
CSS变量之var()函数的应用——动态修改样式 & root的使用
flex相关知识
场景: 动态设置给父元素内子元素设置每行排列几个
通过 document.body.style.setProperty('--itemNum', 5)
设置样式变量,然后通过给父元素设置display: flex;
,子元素设置flex: 0 0 calc(90% / var(--itemNum))
动态控制子元素的宽度
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
.content {
display: flex;
flex-wrap: wrap;
justify-content: flex-start;
padding-bottom: 50px;
padding-left: 40px;
text-align: center;
border:1px solid black;
}
.child {
width: 100px;
height: 100px;
box-sizing: border-box;
flex: 0 0 calc(90% / var(--itemNum));
text-align: center;
background-color: #d8ffff;
border-radius: 47px;
margin: 20px 0;
margin-right:calc(10% / var(--itemNum));
}
</style>
<body>
<div class="content">
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
</div>
</body>
<script>
document.body.style.setProperty('--itemNum', 5)
</script>
</html>