在CSS布局中,实现垂直居中、相同高度的列等一直是令人头疼的问题,但不管是什么布局,Flex往往都可以几行命令搞定;93%的人现在正在运行的浏览器都已经支持Flexbox,这比支持HTML5 的<video>
元素要好;所以现在我们一起来见证Flexbox的神奇,看看利用Flex如何实现骰子布局。
1.单项目
<div class="first-face">
<span class="dot"></span>
</div>
首先,只有左上角1个点的情况。Flex布局默认就是首行左对齐,所以一行代码就够了。
/*单项目1*/
.first-face {
display: flex;
}
设置项目的对齐方式,就能实现居中对齐和右对齐。
/*单项目2*/
.first-face {
display: flex;
justify-content: center;
}
/*单项目3*/
.first-face {
display: flex;
justify-content: flex-end;
}
/*单项目4*/
.first-face {
display: flex;
justify-content: center;
align-items: center;
}
/*单项目5*/
.first-face {
display: flex;
justify-content: center;
align-items: flex-end;
}
/*单项目6*/
.first-face {
display: flex;
justify-content: flex-end;
align-items: flex-end;
}
2.双项目
<div class="second-face">
<span class="dot"></span>
<span class="dot"></span>
</div>
/*双项目1*/
.second-face {
display: flex;
justify-content: space-between;
}
/*双项目2*/
.second-face {
display: flex;
flex-direction: column;
justify-content: space-between;
}
/*双项目3*/
.second-face {
display: flex;
flex-direction: column;
justify-content: space-between;
align-items: center;
}
/*双项目4*/
.second-face {
display: flex;
flex-direction: column;
justify-content: space-between;
align-items: flex-end;
}
/*双项目5*/
.second-face {
display: flex;
}
.second-face .dot:nth-of-type(2) {
align-self: center;
}
/*双项目6*/
.second-face {
display: flex;
justify-content: space-between;
}
.second-face .dot:nth-of-type(2) {
align-self: flex-end;
}
3.三项目
<div class="third-face">
<span class="dot"></span>
<span class="dot"></span>
<span class="dot"></span>
</div>
/*三项目*/
.third-face {
display: flex;
}
.third-face .dot:nth-of-type(2) {
align-self: center;
}
.third-face .dot:nth-of-type(3) {
align-self: flex-end;
}
4.四项目
<div class="fourth-face">
<div class="column">
<span class="dot"></span>
<span class="dot"></span>
</div>
<div class="column">
<span class="dot"></span>
<span class="dot"></span>
</div>
</div>
/*四项目*/
.fourth-face {
display: flex;
justify-content: space-between;
}
.fourth-face .column {
display: flex;
flex-direction: column;
justify-content: space-between;
}
5.五项目
<div class="fifth-face">
<div class="column">
<span class="dot"></span>
<span class="dot"></span>
</div>
<div class="column">
<span class="dot"></span>
</div>
<div class="column">
<span class="dot"></span>
<span class="dot"></span>
</div>
</div>
/*五项目*/
.fifth-face {
display: flex;
}
.fifth-face .column {
display: flex;
flex-direction: column;
justify-content: space-between;
}
.fifth-face .column:nth-of-type(2) {
align-self: center;
}
6.六项目
<div class="sixth-face">
<div class="column">
<span class="dot"></span>
<span class="dot"></span>
<span class="dot"></span>
</div>
<div class="column">
<span class="dot"></span>
<span class="dot"></span>
<span class="dot"></span>
</div>
</div>
/*六项目*/
.sixth-face {
display: flex;
justify-content: space-between;
}
大合照
源代码详见 codepen.