用 flex 实现骰子布局
一、骰子的布局
基本样式
html
<div class="box">
<span class="item"></span>
</div>css
.box {
margin: 100px auto;
width: 100px;
height: 100px;
border-radius: 5px;
background-color: bisque;
}
.item {
display: inline-block;
width: 25px;
height: 25px;
border-radius: 12px;
margin: 2px;
background-color: #800;
}上面代码中,div 元素(代表骰子的一个面)是 Flex 容器,span 元素(代表一个点)是 Flex 项目。如果有多个项目,就要添加多个 span 元素,以此类推。
单项目
左上角
首先是一个点在左上角的情况,flex 布局默认就是左对齐的,因此一行代码就够了。
css
display: flex;水平居中
css
display: flex;
justify-content: center;右上角
css
display: flex;
justify-content: end;垂直居中靠左
css
display: flex;
align-items: center;水平垂直居中
css
display: flex;
justify-content: center;
align-items: center;垂直居中靠右
css
display: flex;
justify-content: end;
align-items: center;左下角
css
display: flex;
align-items: flex-end;水平居中靠下
css
display: flex;
justify-content: center;
align-items: flex-end;右下角
css
display: flex;
justify-content: end;
align-items: flex-end;双项目
布局样式一
css
display: flex;
justify-content: space-between;
align-items: center; /* 通过align-items来控制垂直方向位置 */布局样式二
css
display: flex;
justify-content: space-between;
flex-direction: column; /* 改变主轴方向 */
align-items: start; /* 通过align-items来控制水平方向位置 */布局样式三
css
.box {
display: flex;
}
.item:nth-child(2) {
align-self: center;
}css
.box {
display: flex;
justify-content: space-between;
}
.item:nth-child(2) {
align-self: center;
}三项目
css
.box {
display: flex;
}
.item:nth-child(2) {
align-self: center;
}
.item:nth-child(3) {
align-self: flex-end;
}四项目
html
<div class="box">
<div class="column">
<span class="item"></span>
<span class="item"></span>
</div>
<div class="column">
<span class="item"></span>
<span class="item"></span>
</div>
</div>css
.box {
display: flex;
flex-wrap: wrap;
align-content: space-between;
}
.column {
flex-basis: 100%;
display: flex;
justify-content: space-between;
}