一、单个盒子
页面主体HTML代码如下,此处用两个盒子示例:
<div class="father">
<div class="son"></div>
</div>
为方便展示,定义CSS基础样式如下:
.father {
width: 300px;
height: 300px;
background-color: bisque;
}
.son {
width: 100px;
height: 100px;
background-color: black;
}
1、左对齐
为父盒子添加以下代码
display: flex;
justify-content: flex-start;
.father {
width: 300px;
height: 300px;
background-color: bisque;
display: flex;
justify-content: flex-start;
}
2、右对齐
为父盒子添加以下代码
display: flex;
justify-content: flex-end;
.father {
width: 300px;
height: 300px;
background-color: bisque;
display: flex;
justify-content: flex-end;
}
3、居中对齐
为父盒子添加以下代码
display: flex;
justify-content: center;
.father {
width: 300px;
height: 300px;
background-color: bisque;
display: flex;
justify-content: center;
}
4、水平垂直居中
为父盒子添加以下代码
display: flex;
justify-content: center;
align-items: center;
.father {
width: 300px;
height: 300px;
background-color: bisque;
display: flex;
justify-content: center;
align-items: center;
}
5、底部左对齐
为父盒子添加以下代码
display: flex;
justify-content: flex-start;
align-items: flex-end;
.father {
width: 300px;
height: 300px;
background-color: bisque;
display: flex;
justify-content: flex-start;
align-items: flex-end;
}
6、底部右对齐
为父盒子添加以下代码
display: flex;
justify-content: flex-end;
align-items: flex-end;
.father {
width: 300px;
height: 300px;
background-color: bisque;
display: flex;
justify-content: flex-end;
align-items: flex-end;
}
7、底部居中对齐
为父盒子添加以下代码
display: flex;
justify-content: center;
align-items: flex-end;
.father {
width: 300px;
height: 300px;
background-color: bisque;
display: flex;
justify-content: center;
align-items: flex-end;
}
二、两个盒子
页面主体HTML代码如下,此处用三个盒子示例:
<div class="father">
<div class="son1"></div>
<div class="son2"></div>
</div>
为方便展示,定义CSS基础样式如下:
.father {
width: 300px;
height: 300px;
background-color: bisque;
}
.son1,
.son2 {
width: 100px;
height: 100px;
background-color: black;
}
1、左右两端对齐
为父盒子添加以下代码
display: flex;
justify-content: space-between;
.father {
width: 300px;
height: 300px;
background-color: bisque;
display: flex;
justify-content: space-between;
}
2、左右两端中间对齐
为父盒子添加以下代码
display: flex;
justify-content: space-between;
align-items: center;
.father {
width: 300px;
height: 300px;
background-color: bisque;
display: flex;
justify-content: space-between;
align-items: center;
}
3、左右两端底部对齐
为父盒子添加以下代码
display: flex;
justify-content: space-between;
align-items: flex-end;
.father {
width: 300px;
height: 300px;
background-color: bisque;
display: flex;
justify-content: space-between;
align-items: flex-end;
}