所有css
body{
background-color: honeydew;
}
- 1、absolute + 负margin
<div class="father1">
<div class="method1">
</div>
</div>
.father1{
width: 500px;
height: 500px;
background-color: brown;
position: relative; /* 父元素相对定位,否则子元素相对再往上层找的定位元素居中 */
}
.method1{
width: 200px; /* 宽高固定 */
height: 100px;
position: absolute;
top: 50%; /* 绝对定位,左上角在正中间 */
left: 50%;
margin-left: -100px; /* 各取负一半的margin */
margin-top: -50px;
background-color: bisque;
}
- 2、absolute + margin auto
.father2{
width: 500px;
height: 500px;
background-color: brown;
position: relative;
}
.method2{
width: 200px;
height: 100px;
background-color: bisque;
position: absolute; /* 绝对定位,上下左右0,margin自动auto */
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
html结构同1,效果图同1
- 3、absolute + calc
.method3{
width: 200px;
height: 100px;
background-color: bisque; /* */
position: absolute; /* 绝对定位,位置利用cala动态计算 */
top: calc(50% - 50px);
left: calc(50% - 100px);
}
html结构同1,效果图同1,father3与father1样式相同
- 4、absolute + tramsform
.method4{
width: 200px;
height: 100px;
background-color: bisque; /* */
position: absolute; /* 绝对定位,transform移动位置到正中间 */
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
html结构同1,效果图同1,father3与father1样式相同
- 5、line-height + text-align + inline-block + vertial-align
.father5{
background-color: brown;
line-height: 300px;
text-align: center; /* 水平居中 */
}
.method5{
width: 200px;
height: 100px;
background-color: bisque; /* */
display: inline-block;
vertical-align: middle; /* 垂直居中 */
line-height: initial;
text-align: left; /* 修正文字 */
}
html结构同1
- 6、table-cell
.father6{
display: table-cell; /* table布局,水平垂直居中 */
text-align: center;
vertical-align: middle;
background-color: brown;
width: 500px;
height: 500px;
}
.method6{
width: 200px;
height: 100px;
background-color: bisque; /* */
display: inline-block;
}
html结构同1,效果图同1
- 7、flex
.father7{
display: flex; /* flex弹性布局,利用下面两个属性居中 */
justify-content: center;
align-items: center;
background-color: brown;
width: 500px;
height: 500px;
}
.method7{
width: 200px;
height: 100px;
background-color: bisque; /* */
}
html结构同1,效果图同1
- 8、grid
.father8{
display: grid; /* 栅格布局 */
background-color: brown;
width: 500px;
height: 500px;
}
.method8{
align-self: center; /* 栅格布局,子元素设置水平垂直居中 */
justify-self: center;
width: 200px;
height: 100px;
background-color: bisque; /* */
}
html结构同1,效果图同1