行内元素的居中水平居中text-align:center;
content
.parent{
background-color: red;
text-align: center;
}
fit-content;
content
.parent{
background-color: red;
width: fit-content;/*父元素适应子元素的宽度*/
margin: auto;
}
垂直居中line-height;(只针对单行文本)
content
.parent{
background-color: red;
height: 200px;
line-height: 200px;
}
块级元素的居中水平居中
*margin:0 auto;
.parent{
background-color: red;
}
.child{
background-color: blue;
width: 100px;
margin: 0 auto;/*左右自适应*/
}
水平垂直居中定位
.parent{
background-color: red;
position: relative;
height: 200px;
}
.child{
background-color: blue;
width: 100px;
height: 100px;
position: absolute;
left: 50%;
top: 50%;
margin-top: -50px;
margin-left: -50px;
}
2.定位+transform
.parent{
background-color: red;
position: relative;
height: 200px;
}
.child{
background-color: blue;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
/*子元素大小未知*/
}
3.定位+margin
.parent{
background-color: red;
position: relative;
height: 200px;
}
.child{
background-color: blue;
width: 100px;
height: 100px;
position: absolute;
margin: auto;
left: 0;
right: 0;
top: 0;
bottom: 0;
}
4.padding
.parent{
padding: 20px;
background-color: red;
}
.child{
height: 200px;
background-color: blue;
}
5.flex
.parent{
display: flex;
height: 200px;
align-items: center;
justify-content: center;
background-color: red;
}
.child{
height: 100px;
width: 100px;
background-color: blue;
}
6.伪元素
7.函数calc