1、水平居中
1.1 固定宽度
<div class="content"></div>
.content {
margin: 0 auto;
width: 200px;
height: 200px;
background: gray;
}
1.2 不固定宽度
方法一:display:table;
<div class='content'>水平居中</div>
.content {
display: table;
margin: 0 auto;
background: gray;
}
方法二:display:inline-block;
<div class="center">
<div class="inner">1</div>
<div class="inner">2</div>
</div>
.center {
text-align: center;
}
.inner {
display: inline-block;
}
方法三:transform: translateX(-50%);
<div id="father">
<div id="son">我是块级元素</div>
</div>
#father {
position: relative;
}
#son {
background-color: green;
position: absolute;
left: 50%;
transform: translateX(-50%);
}
方法四:justify-content: center;
<div id="father">
<div id="son">我是块级元素</div>
</div>
#father {
display: flex;
justify-content: center;
}
#son {
background-color: green;
}
2、垂直居中
2.1 固定宽度
<div id="father">
<span id="son">我是多行的行内元素我是多行的行内元素我是多行的行内元素我是多行的行内元素我是多行的行内元素我是多行的行内元素我是多行的行内元素我是多行的行内元素</span>
</div>
#father {
width: 500px;
height: 300px;
background-color: skyblue;
display: table-cell;
vertical-align:middle;
}
#son {
background-color: green;
}
2.2 不固定宽度
方法一:transform: translateY(-50%);
<div id="father">
<div id="son">我是块级元素</div>
</div>
#father {
position: relative;
height:100vh;
}
#son {
background-color: green;
position: absolute;
top: 50%;
transform: translateY(-50%);
}
方法二:align-items: center;
<div id="father">
<div id="son">我是块级元素</div>
</div>
#father {
width: 500px;
height: 300px;
background-color: skyblue;
display: flex;
align-items: center;
}
#son {
width: 100px;
height: 100px;
background-color: green;
}
3、水平垂直居中
方法一:transform: translate(-50%, -50%);
<div class="content"></div>
.content {
width: 100px;
height: 100px;
background: pink;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
方法二:justify-content: center; align-items: center;
<div id="father">
<div id="son">我是块级元素</div>
</div>
#father {
width: 500px;
height: 300px;
background-color: skyblue;
display: flex;
justify-content: center;
align-items: center;
}
#son {
background-color: green;
}