我想布局一组类为cards
的div,并由一个类为card-wrapper
的div集中,而最后一行中的其余.cards
则要向左对齐,如线框所示。
这个想法是,如果我的屏幕宽度很窄,则布局可以变成3或2甚至1列,但是整个包装器始终居中,但最后一行中的.cards
要向左对齐。>
这是我的代码。
CSS
body{
width: 100%;
margin: 0 auto;
display: flex;
flex-direction: row;
text-align: center;
justify-content: center;
align-items: center;
background: #f2f2f2;
}
.cards-wrapper{
background: #fff;
width: 90%;
margin: 0 auto;
display: flex;
flex-direction: row;
flex-wrap: wrap;
justify-content: center;
align-items: center;
}
.card{
width: 20%;
height: 300px;
background: #eee;
margin-bottom: 20px;
margin: 20px;
text-align: left;
}
HTML
<div class="cards-wrapper">
<div class="card">1</div>
<div class="card">2</div>
<div class="card">3</div>
<div class="card">4</div>
<div class="card">5</div>
<div class="card">6</div>
<div class="card">7</div>
<div class="card">8</div>
<div class="card">9</div>
</div>
答案 0 :(得分:0)
请添加以下代码,如下所示。
HTML
<div class="cards-wrapper">
<div class="cards-wrapper-inner">
<div class="card">1</div>
<div class="card">2</div>
<div class="card">3</div>
<div class="card">4</div>
<div class="card">5</div>
<div class="card">6</div>
<div class="card">7</div>
<div class="card">8</div>
<div class="card">9</div>
</div>
</div>
CSS
body{
width: 100%;
margin: 0 auto;
display: flex;
flex-direction: row;
text-align: center;
justify-content: center;
align-items: center;
background: #f2f2f2;
}
.cards-wrapper{
background: #fff;
width: 90%;
margin: 0 auto;
}
.cards-wrapper-inner {
display: flex;
flex-direction: row;
flex-wrap: wrap;
/*justify-content: center;*/
align-items: center;
width: 93%;
margin: 0 auto
}
.card{
width: 20%;
height: 300px;
background: #eee;
margin-bottom: 20px;
margin: 20px;
text-align: left;
}
答案 1 :(得分:0)
if you can support it使CSS Grid非常容易。
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body{
width: 100%;
height: 100vh;
display: flex;
text-align: center;
justify-content: center;
align-items: center;
background: #f2f2f2;
}
.cards-wrapper{
padding: 20px;
background: #fff;
width: 400px;
margin: 0 auto;
/* change display to grid and set up columns, gaps, etc. */
display: grid;
grid-template-columns: repeat(4, auto);
grid-gap: 20px;
}
.card{
height: 40px;
background: #eee;
text-align: left;
}
<div class="cards-wrapper">
<div class="card">1</div>
<div class="card">2</div>
<div class="card">3</div>
<div class="card">4</div>
<div class="card">5</div>
<div class="card">6</div>
<div class="card">7</div>
<div class="card">8</div>
<div class="card">9</div>
</div>
请注意,您可以通过媒体查询来更改grid-template-columns
的值,以匹配您希望用于较窄屏幕的列数。