首先定义两个盒子,并添加基础样式
<div class="father">
<div class="son"></div>
</div>
<style>
1. {
padding: 0;
margin: 0;
}
.father {
height: 200px;
width: 800px;
background-color: skyblue;
}
.son {
height: 100px;
width: 200px;
background-color: orange;
}
</style>
水平居中
- flex布局
.father {
display: flex;
justify-content: center;
}
- 子绝父相 + transform
.father {
position: relative;
}
.son {
position: absolute;
left: 50%;
transform: translateX(-50%);
}
- inline-block + text-align:center
.father {
text-align: center;
}
.son {
display: inline-block;
}
- flex + margin: 0 auto
.father {
display: flex;
}
.son {
margin: 0 auto;
}
- table + margin: 0 auto
.son {
display: table;
margin: 0 auto;
}
样式:
垂直居中
- flex布局
.father {
display: flex;
align-items: center;
}
- 子绝父相 + transform
.father {
position: relative;
}
.son {
position: absolute;
top: 50%;
transform: translateY(-50%);
}
- flex + margin: auto 0
.father {
display: flex;
}
.son {
margin: auto 0;
}
- table-cell + vertical-align: middle
.father {
display: table-cell;
vertical-align: middle;
}
样式:
水平垂直居中
- flex布局
.father {
display: flex;
align-items: center;
justify-content: center;
}
- 子绝父相 + transform
.father {
position: relative;
}
.son {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
- flex + margin: auto
.father {
display: flex;
}
.son {
margin: auto;
}
- inline-block + text-align: center + table-cell + vertical-align: middle
.father {
display: table-cell;
vertical-align: middle;
text-align: center;
}
.son {
display: inline-block;
}
样式:
最后解释一下margin:auto
块级元素设置居中的前提是设置了width,若在css中没写width则会默认占据100%的宽度。auto是指平分剩余空间。
如果单单使用margin:auto是不能实现垂直方向上的居中的,因为默认垂直方向上是没有剩余空间的,这里有两种方法使margin:auto在垂直方向上平分剩余空间
- 子绝父相后 + margin:auto,子元素四边都设为0,子元素会填充真个父元素的所有剩余空间
.father {
position: relative;
}
.son {
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
}
- flex + margin:auto,可以快速实现水平垂直居中(推荐flex布局,很方便)