水平居中:
1.行级元素:设置父元素的text-align:center
<style>
.container {
background-color: blue;
height: 500px;
text-align: center;
}
.container .box {
background-color: red;
}
</style>
</head>
<body>
<div class="container">
<span class="box">111</span>
</div>
</body>
2.块级元素:设置当前块级元素(有宽度)margin: 0 auto;
<style>
.container {
background-color: blue;
height: 500px;
}
.container .box {
background-color: red;
height: 100px;
width: 100px;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="container">
<div class="box">111</div>
</div>
</body>
3.绝对定位:元素有宽度的情况下,left: 0; right: 0; margin: 0 auto;
<style>
.container {
position: relative;
background-color: blue;
height: 500px;
}
.container .box {
background-color: red;
height: 100px;
width: 100px;
position: absolute;
left: 0;
right: 0;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="container">
<div class="box">111</div>
</div>
</body>
4.flex布局:设置父元素justify-content:center
<style>
.container {
display: flex;
justify-content: center;
background-color: blue;
height: 500px;
}
.container .box {
background-color: red;
height: 100px;
}
</style>
</head>
<body>
<div class="container">
<div class="box">111</div>
</div>
</body>
垂直居中:
1.绝对定位:元素有高度的情况下,top: 0; bottom: 0; margin: auto 0;
<style>
.container {
position: relative;
background-color: blue;
height: 500px;
}
.container .box {
background-color: red;
height: 100px;
position: absolute;
top: 0;
bottom: 0;
margin: auto 0;
}
</style>
</head>
<body>
<div class="container">
<div class="box">111</div>
</div>
</body>
弊端:脱离标准流,必须给元素设置高度
2.flex布局:设置父元素align-items: center;
<style>
.container {
display: flex;
align-items: center;
background-color: blue;
height: 500px;
width: 100%;
}
.container .box {
background-color: red;
height: 100px;
width: 100px;
}
</style>
</head>
<body>
<div class="container">
<div class="box"></div>
</div>
</body>
弊端:当前flex布局中所有元素都会被垂直居中,相对来说兼容性差
3.top/translate
- 让元素向下位移父元素的50%
- 让元素向上位移自身的50%
<style>
.container {
background-color: blue;
height: 500px;
}
.container .box {
background-color: red;
height: 100px;
position: relative;
top: 50%;
transform: translateY(-50%);
}
</style>
</head>
<body>
<div class="container">
<div class="box">111</div>
</div>
</body>