由于我们在布局中经常会用到垂直居中块级元素或者行内元素,在这里小编来做一个总结。
块级元素水平居中:
方法一:
直接给子元素添加样式:margin: 0 auto;
.father {
width: 200px;
height: 200px;
background-color: red;
}
.son {
width: 150px;
height: 150px;
background-color: pink;
margin: 0 auto;
}
<div class="father">
<div class="son">
</div>
</div>
效果:
方法二:
利用绝对定位让子元素先右移50%,由于子元素有自己的宽度,导致子元素并没有达到居中效果这时我们需要借助样式 transform: translateX(-50%);让子元素在向左移动自身的一半,这样就达到了居中效果。
注意 !! 不要忘记子绝父相。
(万能居中方法,不管是行内块元素,行内元素,还是块级元素都可以达到居中效果) 因为当使用绝对定位后将行内块元素和行内元素都转换成为了块级元素!
.father {
position: relative;
width: 200px;
height: 200px;
background-color: red;
}
.son {
position: absolute;
left: 50%;
transform: translateX(-50%);
width: 150px;
height: 150px;
background-color: pink;
}
<div class="father">
<div class="son">
</div>
</div>
效果:
方法三:
利用弹性布局让主轴元素直接居中的样式,但是由于有浏览器兼容问题,建议在移动端使用。
.father {
display: flex;
justify-content: center;
width: 200px;
height: 200px;
background-color: red;
}
.son {
width: 150px;
height: 150px;
background-color: pink;
}
<div class="father">
<div class="son">
</div>
</div>
效果:
行内元素水平居中:
方法一:
直接给行内元素父元素添加样式:text-align: center;,可以使父元素里面的行内元素全部居中 (包括行内块元素)
.father {
width: 200px;
height: 200px;
background-color: red;
text-align: center;
}
.son {
background-color: pink;
}
<div class="father">
<span class="son">
Hello word!
</span>
</div>
</body>
效果:
块级元素竖直居中:
方法一:
利用弹性布局让主轴元素直接居中的样式,建议在移动端使用。(原理和水平居中一样)
.father {
display: flex;
align-items: center;
width: 200px;
height: 200px;
background-color: red;
}
.son {
width: 150px;
height: 150px;
background-color: pink;
}
<div class="father">
<div class="son"></div>
</div>
效果:
方法二:
利用绝对定位让子元素先向下移50%,由于子元素有自己的宽度,导致子元素并没有达到居中效果这时我们需要借助样式 transform: translateY(-50%);让子元素在向上移动自身的一半,这样就达到了居中效果。
注意 !! 不要忘记子绝父相。
.father {
position: relative;
width: 200px;
height: 200px;
background-color: red;
}
.son {
position: absolute;
top: 50%;
transform: translateY(-50%);
width: 150px;
height: 150px;
background-color: pink;
}
<div class="father">
<div class="son">
</div>
</div>
效果:
行内元素竖直居中:
方法一:
直接给行内元素父元素添加样式:line-height: 200px;
.father {
width: 200px;
height: 200px;
background-color: red;
line-height: 200px;
}
.son {
width: 150px;
height: 150px;
background-color: pink;
}
<div class="father">
<span class="son">
hello Word!
</span>
</div>
效果:
块级元素垂直居中:
方法一:
利用flex布局,将竖直居中和水平居中结合起来使用。
.father {
display: flex;
justify-content: center;
align-items: center;
width: 200px;
height: 200px;
background-color: red;
}
.son {
width: 150px;
height: 150px;
background-color: pink;
}
<div class="father">
<div class="son">
</div>
</div>
效果:
方法二:
利用定位,将盒子垂直居中起来。
.father {
position: relative;
width: 200px;
height: 200px;
background-color: red;
}
.son {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
width: 150px;
height: 150px;
background-color: pink;
}
效果:
行内元素垂直居中:
方法一:
将行高和文本居中结合起来使用
.father {
width: 200px;
height: 200px;
background-color: red;
text-align: center;
line-height: 200px;
}
.son {
background-color: pink;
}
<div class="father">
<span class="son">
hello World!
</span>
</div>
效果: