CSS实现居中的方式
<div class="out">
<div class="in"></div>
</div>
1、水平居中
- 通过margin: 0 auto; 实现水平居中
.out{
width: 600px;
height: 600px;
background: cornflowerblue;
}
.in{
width: 100px;
height: 100px;
background: chartreuse;
margin: 0 auto;
}
- 通过position:absolute + margin-left 实现水平居中
.out {
height: 400px;
width: 400px;
background: cadetblue;
position: relative;
}
.in {
width: 100px;
height: 100px;
background: greenyellow;
position: absolute;
left: 50%;
margin-left: -50px;
}
- 通过text-align: center 实现水平居中
.out {
height: 400px;
width: 400px;
background: cadetblue;
text-align: center;
}
.in {
width: 100px;
height: 100px;
background: greenyellow;
display: inline-block;
}
- 通过隐藏节点+float的方法实现水平居中
<div class="out">
<div class="a"></div>
<div class="in"></div>
</div>
.out{
width: 600px;
height: 600px;
background: cornflowerblue;
}
.out .a{
content: "";
height: 50%;
width: 25%;
float: left;
}
.in{
width: 50%;
height: 50%;
background: chartreuse;
float: left;
}
2.垂直居中
- 通过position:absolute实现CSS垂直居中。
.out {
height: 400px;
width: 400px;
background: cadetblue;
position: relative;
}
.in {
width: 100px;
height: 100px;
background: greenyellow;
position: absolute;
top: 50%;
margin-top: -50px;
}
- 当垂直居中的块级元素高度未知时,
可以借助CSS3中的transform属性向Y轴反向偏移50%的方法实现垂直居中,部分浏览器可能存在兼容性问题。
.out {
height: 400px;
width: 400px;
background: cadetblue;
position: relative;
}
.in{
width: 100px;
height: 100px;
background: greenyellow;
position: absolute;
top: 50%;
transform: translateY(-50%);
}
- 通过隐藏节点实现CSS垂直居中
<div class="out">
<div class="a"></div>
<div class="in"></div>
</div>
.out{
width: 600px;
height: 600px;
background: cornflowerblue;
}
.out .a{
content: "";
height: 25%;
width: 50%;
}
.in{
width: 50%;
height: 50%;
background: chartreuse;
}
3.垂直水平居中
- 通过 position: absolute + margin: auto 实现垂直水平居中
.out{
width: 600px;
height: 600px;
background: cornflowerblue;
position: relative;
}
.in{
width: 100px;
height: 100px;
background: chartreuse;
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
margin: auto;
}
- 通过position:absolute + margin 实现垂直水平居中
.out {
height: 400px;
width: 400px;
background: cadetblue;
position: relative;
}
.in {
width: 100px;
height: 100px;
background: greenyellow;
position: absolute;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -50px;
}
- 使用transform: translate 实现垂直水平居中
.out {
height: 400px;
width: 400px;
background: cadetblue;
position: relative;
}
.in {
width: 100px;
height: 100px;
background: greenyellow;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
- 对行盒:使用 text-align: center + line-height 实现垂直水平居中
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.text{
height: 400px;
width: 400px;
background: cadetblue;
text-align: center;
line-height: 400px;
}
</style>
</head>
<body>
<div class="text">
Lorem ipsum dolor sit.
</div>
</body>
</html>