-
行内元素居中(文本,链接等)
text-align: center;
.container{
width: 50%;
border: 1px solid black;
text-align: center;
}
此种方法可以让行内元素居中, 包括类型有inline/ inline-block/ inline-table/ flex
display: flex; justify-content: center;
.container{
width: 30%;
border: 1px solid black;
display: flex;
justify-content: center;
}
- 块级元素体居中
- 使用
flex
.container{
width: 550px;
height: 80px;
border: 1px solid black;
display: flex;
justify-content: center;
align-items: center;
}
- 使用
margin: 0 auto实现水平居中
.container{
width: 550px;
height: 80px;
border: 1px solid black;
}
.box1{
background-color: cornflowerblue;
width: 200px;
height: 30px;
margin: 0 auto;
}
- 已知元素高度,使用
position: absolute
.container{
width: 550px;
height: 80px;
border: 1px solid black;
position: relative;
/* padding: 10px; */
}
.box1{
background-color: cornflowerblue;
width: 200px;
height: 30px;
position: absolute;
left: 50%;
top:50%;
margin-top: -15px;
margin-left: -100px;
}
- 未知元素高度,使用
transform: translateY(-50%, -50%)实现居中
.container{
width: 550px;
height: 80px;
border: 1px solid black;
position: relative;
}
.box1{
background-color: cornflowerblue;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}



