-
行內(nèi)元素居中(文本,鏈接等)
text-align: center;
.container{
width: 50%;
border: 1px solid black;
text-align: center;
}
此種方法可以讓行內(nèi)元素居中, 包括類型有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
實現(xiàn)水平居中
.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%)
實現(xiàn)居中
.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%);
}