水平垂直居中的常见实现方式
前言
本文记录四种在CSS中常见的,实现水平垂直居中的方式,这些知识属于偏记忆性的东西,经常写就不会忘,隔一段时间没看的话有时候就想不起细节了。
所以,本文的主要目的还是做记录,方便忘记时回顾复习。
首先,我们应该考虑的是要实现垂直居中的元素,它是行内元素,还是块级元素。
对于行内元素来说,实现方式就比较简单了:水平居中用text-align: center
;垂直居中把line-height
的值设置为 height
的值行了。
下面主要来写一下对于块级元素的垂直居中实现方式
一,使用 flex 布局
代码如下:
<!-- 方式一 flex 布局 -->
<div class="father-flex">
<div class="son-flex">son</div>
</div>
/* 方式一 flex布局 */
.father-flex {
width: 200px;
height: 200px;
margin: 20px 20px;
background-color: #ccc;
/* 核心代码 */
display: flex;
justify-content: center;
align-items: center;
}
.son-flex {
width: 50px;
height: 50px;
background-color: #abc;
}
二,absolute margin auto 布局(不需要知道宽高,也不用考虑兼容性)
代码如下:
<!-- 方式二 absolute margin auto -->
<div class="father-relative">
<div class="son-absolute">son</div>
</div>
/* 方式二 absolute margin auto 布局 (不需要知道宽高,也不用考虑兼容性) */
.father-relative {
width: 200px;
height: 200px;
margin: 20px 20px;
background-color: #ccc;
position: relative;
}
.son-absolute {
width: 50px;
height: 50px;
background-color: #abc;
/* 核心代码 */
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
}
三,通过设置top,left 50% 以及 margin 负值(需要知道宽高,否则margin负值无法设置)
代码如下:
<!-- 方式三 通过设置top/left 50% 以及 margin 负值 -->
<div class="father-50">
<div class="son-50">son</div>
</div>
/* 方式三 通过设置top/left 50% 以及 margin 负值 (需要知道宽高,否则margin负值无法设置)*/
.father-50 {
width: 200px;
height: 200px;
margin: 20px 20px;
background-color: #ccc;
position: relative;
}
.son-50 {
width: 50px;
height: 50px;
background-color: #abc;
/*核心代码*/
position: absolute;
top: 50%;
left: 50%;
margin-left: -25px;
margin-top: -25px;
}
四,设置 transform: translate(-50%, -50%)
CSS3特性,需要考虑兼容性
代码如下:
<!-- 方式四 设置transform: translate(-50%, -50%)-->
<div class="father-translate">
<div class="son-translate">son</div>
</div>
/* 方式四 设置transform: translate(-50%, -50%) CSS3特性,需要考虑兼容性 */
.father-translate {
width: 200px;
height: 200px;
margin: 20px 20px;
background-color: #ccc;
position: relative;
}
.son-translate {
width: 50px;
height: 50px;
background-color: #abc;
/*核心代码*/
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
总结归纳:
- 方式一是 flex 布局,知道
justify-content
和align-items
就行,前者是决定主轴的方向(即项目的排列方向);后者是 定义项目在交叉轴上如何对齐。 - 方式二,三,四,都需要设置
子绝父相
,在此基础上:- 方式三和方式四 都需要设置
top: 50%; left: 50%
,将子元素往右下移动父元素的一半宽高。然后方式三使用margin为宽高一半的负值
将子元素往中间移,所以需要知道元素的宽高;方式四直接使用CSS3特性transform: translate(-50%, -50%)
将子元素移到中间,所以需要考虑兼容性。 - 方式二将
top bottom left right
都设为0
,然后再设置margin: auto
就可以实现水平垂直居中,这种方式无需知道宽高,也不需要考虑兼容性。
- 方式三和方式四 都需要设置
具体效果图也很简单,四种方式都是一个效果:两个盒子,子盒子水平垂直居中:
以上就是本文全部内容,如有问题,欢迎指正 😄