1.1 垂直居中
1.1 垂直居中
<div class="parent">
<div class="child">hello world</div>
<div>
- position + margin:auto
.parent {
width: 400px;
height: 300px;
position: relative;
}
.child {
width: 300px;
height: 200px;
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
}
- position + translate
.parent {
width: 400px;
height: 300px;
position: relative;
}
.child {
width: 300px;
height: 200px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
- position + 负margin
此 margin 减去的宽高是相对于自身而言的。
.parent {
width: 400px;
height: 300px;
position: relative;
}
.child {
width: 300px;
height: 200px;
position: absolute;
top: 50%;
left: 50%;
margin-top: -100px;
margin-left: -150px;
}
- table
.parent {
width: 400px;
height: 300px;
display: table-cell;
vertical-align: middle;
text-align: center;
}
.child {
display: inline-block;
width: 300px;
height: 200px;
}
- flex
.parent {
display: flex;
justify-content: center;
align-items: center;
}
- gird
自己实现时发现无法垂直居中(结果待定)
.parent {
display: grid;
justify-content: center;
align-items: center;
}
- 单行文本
height: 10px;
line-height: 10px;
text-align: center;
1.2 水平居中
- 定宽:margin:0 auto
.parent {
width: 300px;
height: 300px;
background: red;
}
.child {
width: 200px;
height: 100px;
background: green;
margin: 0 auto;
}
- 绝对定位 + left: 50% + margin: 负自身一半
.parent {
width: 300px;
height: 300px;
background: red;
position: relative;
}
.child {
width: 200px;
height: 100px;
background: green;
position: absolute;
left: 50%;
margin-left: -100px;
}
- text-align + inline-block
text-align 中的属性值是对于级联元素而言的,如果子元素是块级元素,那么此块级元素是无法实现上述效果的。
.parent {
width: 300px;
height: 300px;
background: red;
text-align: center;
}
.child {
display: inline-block;
width: 200px;
height: 100px;
background: green;
}
1.3 垂直居中
- position: absolute
.parent {
width: 300px;
height: 300px;
background: red;
position: relative;
}
.child {
width: 200px;
height: 100px;
background: green;
position: absolute;
top: 50%;
margin-top: -50px;
}
- table-cell + vertical-align
.parent {
width: 300px;
height: 300px;
background: red;
display: table-cell;
vertical-align: middle;
}
.child {
width: 200px;
height: 100px;
background: green;
}