# 一、方法介绍
# 1.1仅居中元素定宽高适用
- absolute + 负margin
- absolute + margin auto
- absolute + calc
# 1.2居中元素不定宽高
- absolute + transform
- lineheight
- writing-mode
- table
- css-table
- flex
- grid
# 1.3绝对定位公式
绝对定位公式:
定位参照对象的宽度 = left + right + margin-letf +margin-right+ 绝对定位元素占用宽度
定位参照对象的高度 = top + bottom + margin-top +margin-bottom +绝对定位元素占用高度
margin默认都为0
# 二、垂直居中
# 2.1absolute + 负margin
- 需要知道宽高
<div class="box">
<div class="item"></div>
</div>
.box{
position: relative;
width: 300px;
height: 300px;
border: 1px solid red;
}
.item {
position: absolute;
top: 50%;
height: 100px;
width: 100px;
margin-top: -50px;
background-color: orange;
}
# 2.2absolute + margin auto
- 需要知道宽高
.box{
position: relative;
width: 300px;
height: 300px;
border: 1px solid red;
}
.item {
position: absolute;
top: 0;
bottom: 0;
height: 100px;
width: 100px;
margin: auto;
background-color: orange;
}
# 2.3absolute+calc
- 需要知道宽高
.box{
position: relative;
width: 300px;
height: 300px;
border: 1px solid red;
}
.item {
position: absolute;
top: calc(50% - 50px);
height: 100px;
width: 100px;
background-color: orange;
}
# 2.4absolute+transform
- 不需要需要知道宽高
.box{
position: relative;
width: 300px;
height: 300px;
border: 1px solid red;
}
.item {
position: absolute;
height: 100px;
width: 100px;
background-color: orange;
top: 50%;
transform: translateY(-50%);
}
# 2.5line-height
- 要知道父元素的宽度
- 父元素开启line-height,子元素vertical-align:middle
.box {
width: 300px;
height: 300px;
border: 1px solid red;
line-height: 300px;
}
.item {
height: 100px;
width: 100px;
background-color: orange;
vertical-align: middle;
display: inline-block;
}
# 2.6flex
- justfity-content/align-items开启为center
.box {
width: 300px;
height: 300px;
border: 1px solid red;
display: flex;
align-items: center;
}
.item {
height: 100px;
width: 100px;
background-color: orange;
}
# 三、水平居中
与上面类似