需求:内部元素大小是固定的宽高,如何均匀分布在容器中,并且换行不受影响
代码如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
* {
margin: 0;
padding: 0;
list-style: none;
}
html,body {
height: 100%;
}
.container {
height: 100%;
width: 100%;
background: rgb(176, 227, 247);
overflow-y: auto;
}
ul {
display: grid;
grid-gap: 50px; /* 每个网格之间的间距 */
justify-content: space-evenly; /* 均匀平铺 */
grid-template-columns: repeat(auto-fill, 400px); /* 自适应数量 个 宽度为400的列 */
}
ul li {
height: 300px;
background: rgb(252, 250, 251);
}
</style>
<body>
<div class="container">
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</div>
</body>
</html>
关键点:
ul {
display: grid;
grid-gap: 50px; /* 每个网格之间的间距 */
justify-content: space-evenly; /* 均匀平铺 */
grid-template-columns: repeat(auto-fill, 400px); /* 自适应数量 个 宽度为400的列 */
}
使用grid布局,让内部元素在横向自动分配数量,使用 justify-content: space-evenly 使元素均匀分布。