CSS网格:如何将网格项集中在6列的行上



一个客户要求我添加一个"关键人物";网站上的部分,其中每行最多只能有6个关键数字(因为网站连接到CMS,所以可以有更多)

所以我用的是一个CSS网格:

* {
margin: 0;
}
.container {
display: grid;
grid-template-columns: repeat(6, max-content);
justify-content: center;
gap: 3rem;
margin: 3rem auto;
}
.item {
height: 5rem;
width: 5rem;
}
<div class="container">
<div class="item">
<h2>400+</h2>
<p>Lorem ipsum</p>
</div>
<div class="item">
<h2>400+</h2>
<p>Lorem ipsum</p>
</div>
<div class="item">
<h2>400+</h2>
<p>Lorem ipsum</p>
</div>
<div class="item">
<h2>400+</h2>
<p>Lorem ipsum</p>
</div>
<div class="item">
<h2>400+</h2>
<p>Lorem ipsum</p>
</div>
<div class="item">
<h2>400+</h2>
<p>Lorem ipsum</p>
</div>
<div class="item">
<h2>400+</h2>
<p>Lorem ipsum</p>
</div>
<div class="item">
<h2>400+</h2>
<p>Lorem ipsum</p>
</div>
</div>

但客户也要求,如果关键数字少于或多于6个,则项目应居中,而不是向左,如:

如果提供3个关键数字:

X X X

如果提供8个关键数字:

X X X X X X 
X X

如果提供11个关键数字:

X X X X X X
X X X X X

等等

我怎样才能做到这一点?如果网格中的项目少于或多于6个,如何使6列的行以项目为中心?

到目前为止,我让它工作的唯一方法是显示它的flex而不是网格参见片段

<!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>
<style>
* {
margin: 0;
}
.container {
display: flex;
grid-template-columns: repeat(6, max-content);
justify-content: center;
align-items: center;
gap: 3rem;
margin: 3rem auto;
}
.item {
height: 5rem;
width: 5rem;
}
.container2{
display: flex;
justify-content: center;
align-items: center;
}
</style>
</head>
<body>
<div class="container">
<div class="item">
<h2>400+</h2>
<p>Lorem ipsum</p>
</div>

<div class="item">
<h2>400+</h2>
<p>Lorem ipsum</p>
</div>

<div class="item">
<h2>400+</h2>
<p>Lorem ipsum</p>
</div>
<div class="item">
<h2>400+</h2>
<p>Lorem ipsum</p>
</div>

<div class="item">
<h2>400+</h2>
<p>Lorem ipsum</p>
</div>

<div class="item">
<h2>400+</h2>
<p>Lorem ipsum</p>
</div>
</div>
<div class="container2">
<div class="item">
<h2>400+</h2>
<p>Lorem ipsum</p>
</div>

<div class="item">
<h2>400+</h2>
<p>Lorem ipsum</p>
</div>
<div class="item">
<h2>400+</h2>
<p>Lorem ipsum</p>
</div>
<div class="item">
<h2>400+</h2>
<p>Lorem ipsum</p>
</div>
</div>  
</body>
</html>

相关内容

  • 没有找到相关文章

最新更新