需要形容
假如咱们有如下初始代码,要求实现content
在container
中是垂直居中的。
<div class="container"> <div class="content"></div></div>.container { background-color: gray; height: 30rem; /* 高度能够随便变动 */}.content { background-color: wheat; height: 10rem; width: 10rem;}
最终成果:
1.用margin: auto
的办法
原理:
- margin: auto 罕用于设置程度居中。它会为元素主动填充可用空间。
然而对于以下状况不起作用:
元素 | Position |
---|---|
内联元素 | float |
浮动元素 | inline |
块级元素 | absulute/fixed |
- 当咱们通过通过 position:absolute 和 top:0 bottom:0 来给元素的垂直方向拓展设置可用空间, 那么该元素可主动填充父级元素的可用尺寸。
- 代码实现:
.container { position: relative; /* 设置父元素position为relative */}.content { position: absolute; top: 0; /* 设置四个方向是地位为0 */ left: 0; right: 0; bottom: 0; margin: auto; /* 利用margin: auto实现垂直居中 */}
2. 用top: 50%;
+translateY(-50%)
- 原理:
这种形式实现起来比较简单,然而前提是不须要做别的transform
改变。 - 代码实现:
.container { position: relative; /* 设置父元素position为relative */}.content { position: absolute; top: 50%; /* 设置子元素的起始地位为父元素垂直方向50%的地位 */ transform: translateY(-50%); /* 再往上平移子元素高度的50% */ /* 这两条能够同时实现程度居中 transform: translate(-50%, -50%); left: 50% */}
3. display: flex
+margin: auto
- 原理:
flex 容器中默认存在两根轴:主轴和穿插轴。默认的主轴是程度轴。通过管制子元素对这两根轴的对齐形式。能够比拟轻松地实现居中。
将父元素设置为 flex 容器,再加上margin: auto
来同时实现程度和垂直居中。这个办法能够说是最简略的。 - 代码实现:
.container { display: flex; /* 设置父元素设置为flex容器 */}.content { margin: auto;}
4. 通过设置flex
容器的justify-content
和align-items
两个属性来实现
- 原理:
flex 布局中的两个属性justify-content
:定义了元素在主轴的对齐形式,align-items
:定义了元素在穿插轴的对齐形式。
通过把两个对齐形式都设置为center
,来实现居中对齐 - 代码实现
.container { display: flex; justify-content: center; align-items: center;}
5. 通过设置flex
中子元素的align-self
属性
- 原理:
在 flex 布局中,能够通过设置子元素的align-self
来独自定义对齐形式。它和align-items
的区别是:它是定义在子元素上,会笼罩 flex 容器中定义的align-items
属性
- 代码实现
-
.container { display: flex; /* 设置父元素设置为flex容器 */}.content { align-self: center; margin: 0 auto; /* 实现程度居中,flex布局不反对justify-self */}
6. grid
布局+margin:auto
- 原理
grid 网格布局,将元素分为行和列,是一种二维布局。它罕用于实现咱们当初风行的瀑布流显示模式。
在实现居中上,它和 flex 布局实现居中的原理很像。先确认容器,而后再通过相应属性来设置子元素的对齐形式。 - 代码实现
.container { display: grid;}.content { margin: auto;}
7. grid
布局,设置容器的align-content
和justify-items
- 原理
justify-content
属性设置整个内容区域在容器外面的程度地位,align-content
属性设置整个内容在容器的垂直地位。 - 代码实现
.container { display: grid; align-items: center; justify-content: center;}
8. grid
布局中独自设置子元素的对齐形式
- 代码实现
.container { display: grid;}.content { justify-self: center; /* 设置子元素垂直居中 */ align-self: center; /* 设置子元素程度居中*/}
总结:
无论是垂直居中或者程度居中,要点是:
- 先确认参照物,比如说
position:relative
的父元素,flex 容器或者 grid 容器,甚至还有咱们这篇文章中没有提到的 table 布局 - 再依据参照物进行居中,一个是通过
marin:auto
来对可用空间的主动填充。或者是通过一些管制对齐的属性来实现居中。