一、水平居中
1、将元素设置为块级元素
{
display: block;
margin: auto;
}
2、flex布局
{
display: flex;
justify-content: center;
}
3、父元素设置text-align
{
text-align: center;
}
4、设置position
{
position: relative;
left: 50%;
transform: translateX(-50%);
}
二、垂直居中
1、flex布局
{
display: flex;
align-items: center;
}
2、display:table-cell
{
display: table-cell;
vertical-align: middle;
}
3、设置position属性
{
position: relative;
top: 50%;
transform: translateY(-50%);
}
通过设置line-height=父元素高度可以使单行文字实现垂直居中。
三、圆角
{
border-radius: 10px;
}
四、一个div宽度固定,另一个div铺满剩余空间
<div class="wrapper">
<div class="box1"></div>
<div class="box2"></div>
</div>
1、利用flex布局
.wrapper {
display: flex;
}
.box1 {
width: 200px;
height: 200px;
background-color: bisque;
}
.box2 {
flex: 1;
height: 100px;
background-color: blueviolet;
}
2、用浮动布局和overflow属性
.box1 {
width: 200px;
height: 200px;
background-color: bisque;
float: left;
}
.box2 {
background-color: blueviolet;
height: 100px;
overflow: hidden;
}
3、用浮动和左边距
.box1 {
width: 200px;
height: 200px;
background-color: bisque;
float: left;
}
.box2 {
background-color: blueviolet;
height: 100px;
margin-left:0;
}
五、一个div高度固定,另一个div铺满剩余空间
<div class="content">
<div class="top">top</div>
<div class="bottom">bottom</div>
</div>
1、利用flex布局
.content {
width: 500px;
height: 500px;
background-color: brown;
display: flex;
flex-direction: column;
}
.top {
width: 500px;
height: 200px;
background-color: burlywood;
}
.bottom {
flex: 1;
width: 300px;
background-color: cadetblue;
}
2、利用calc计算高度
.content {
width: 500px;
height: 500px;
background-color: brown;
}
.top {
width: 500px;
height: 200px;
background-color: burlywood;
}
.bottom {
width: 300px;
background-color: cadetblue;
height: calc(100% - 200px);
}
3、使用绝对定位
.content {
width: 500px;
height: 500px;
background-color: brown;
position: relative;
}
.top {
width: 500px;
height: 200px;
background-color: burlywood;
}
.bottom {
width: 300px;
background-color: cadetblue;
position: absolute;
bottom: 0;
top: 200px;
}