我怎樣才能實現& quot間距& quot帶有CSS網格的Flexbox的效果?
你可以在下面的鏈接中看到我的代碼:
Codepen - Flexbox和Css網格
.grid-container {
display: grid;
grid-template-columns: repeat(3, 1fr);
border: 1px solid black;
justify-items: center;
}
.flex-container {
display: flex;
justify-content: space-between;
border: 1px solid black;
}
.box {
margin: 10px;
border: 1px solid red;
width: 120px;
height: 120px;
background-color: lightcyan;
text-align: center;
line-height: 120px;
}
<h1>Css Grid</h1>
<section class="grid-container">
<div class="box">Box 1</div>
<div class="box">Box 2</div>
<div class="box">Box 3</div>
</section>
<h1>Flexbox</h1>
<section class="flex-container">
<div class="box">Box 1</div>
<div class="box">Box 2</div>
<div class="box">Box 3</div>
</section>
剛設置邊距:10px自動;開著。柔性容器。盒子。
之后,如果你想創建一個3列,網格,你將需要添加額外的CSS如下演示:
.flex-container {
display: flex;
flex-wrap: wrap; /***** ADDED *****/
border: 1px solid black;
}
.flex-container .box{ /***** ADDED *****/
margin:10px calc(16.5% - 60px);
flex-grow: 1;
max-width:120px;
}
演示
.grid-container {
display: grid;
grid-template-columns: repeat(3, 1fr);
border: 1px solid black;
justify-items: center;
}
.flex-container {
display: flex;
flex-wrap: wrap;
/*justify-content: space-between;*/
border: 1px solid black;
}
.flex-container .box{ /***** ADDED *****/
margin:10px calc(16.5% - 60px);
flex-grow: 1;
max-width:120px;
}
.box{
margin:10px;
border: 1px solid red;
width:120px;
height:120px;
background-color: lightcyan;
text-align: center;
line-height:120px;
}
<h1>Css Grid</h1>
<section class="grid-container">
<div class="box">Box 1</div>
<div class="box">Box 2</div>
<div class="box">Box 3</div>
<div class="box">Box 4</div>
</section>
<h1>Flexbox</h1>
<section class="flex-container">
<div class="box">Box 1</div>
<div class="box">Box 2</div>
<div class="box">Box 3</div>
<div class="box">Box 4</div>
</section>
要制作帶有CSS網格的Flexbox效果: 這不是一個標準的網格,flexbox將是一個顯而易見的解決方案。但是,您可以通過更改網格元素的屬性來實現這一點:
.box {
margin: auto; // changed from 10px to auto
}
.box:first-child {
margin-left: 10px;
}
.box:last-child {
margin-right: 10px;
}
這將確保第一個和最后一個元素緊挨著邊緣,邊距在中心增加。
用Flexbox制作網格效果: 只需在flex容器中更改該屬性: justify-content:space-between;對此:justify-content:space-around; 他們非常自我描述。我覺得不需要額外的信息。
一個簡單的方法是使用瀏覽器檢查工具。
不要用1fr,用auto
.grid-container {
display: grid;
grid-template-columns: repeat(3, auto);
border: 1px solid black;
justify-content: space-between;
}
.flex-container {
display: flex;
justify-content: space-between;
border: 1px solid black;
}
.box {
margin: 10px;
border: 1px solid red;
width: 120px;
height: 120px;
background-color: lightcyan;
text-align: center;
line-height: 120px;
}
<h1>Css Grid</h1>
<section class="grid-container">
<div class="box">Box 1</div>
<div class="box">Box 2</div>
<div class="box">Box 3</div>
</section>
<h1>Flexbox</h1>
<section class="flex-container">
<div class="box">Box 1</div>
<div class="box">Box 2</div>
<div class="box">Box 3</div>
</section>