居中【CSS 知识汇点3】

301 阅读3分钟

在开发过程中,总是难易避免会遇到将元素水平或垂直居中的需求,今天我们就对此进行一次整理。

水平居中

水平居中的9种实现方法

行内元素

给其父元素设置 text-align: center; width: xxxpx ,单个行内元素或多个行内元素都生效;

块级元素

单个块级元素适用:

  1. 元素设置 margin: 0 auto; width: xxxpx;
  2. 使用 absolute + transform;父元素设置:position: relative;, 元素设置position: absolute; left: 50%; transform: translateX(-50%);
  3. 使用flex + margin:父元素设置 display: flex,给元素设置:margin: 0 auto;

多个/单个块级元素水平居中的方法:

  1. 使用table + margin;margin: 0 auto; display: table;

  2. 给父元素设置:display: flex; justify-content: center;

  3. 给其父元素设置text-align:center;给块级元素们设置 display: inline-block

浮动元素

  1. 定宽度的浮动元素,通过元素设置relative + 负margin: 元素设置position: relative; left: 50%; margin-left: -宽度/2 px;
  2. 不定宽的浮动元素,通过父子容器都相对定位:父元素设置:position: rleative; float: left; left: 50%,元素设置position: relative;float: left: right: 50%

垂直居中

垂直居中的7种实现方法

行内元素

行内元素垂直居中: 1. 设置父容器的 line-height 和 height 值一样。 2. 用 flex 布局, 设置父容器:display: flex; height: xxxpx; flex-direction: column;justify-content: center; 3. 用 table 布局,设置父容器 display: table; height: xxxpx; 设置元素:display: table-cell; vertical-align: middle

块级元素

单个块级元素垂直居中: 1. 当已知元素的高度,使用 absolute + 负margin;父元素设置:position: relative; 子元素设置:position: absolute; height:xxxpx; top: 50%; margin-top: -xxx/2px; 2. 当不知元素的高度,使用 position + transform; 父元素设置: position: releative 子元素设置: position: absolute; top; 50%; transform: translateY(-50%)

单个/多个块级元素垂直居中的方法: 1. 使用flex + align-items: 父元素设置:display: flex; align-items: center; 2. 给其父元素设置text-align:center;给块级元素们设置 display: inline-block

水平垂直居中

水平垂直居中的8种实现方法

不定宽高元素

  1. vetrical-align + line-height: 父元素设置vetrical-align: middle; text-align: center; height: xxxpx;,设置元素 line-height: xxxpx
  2. absolute + transform: 父元素设置:position: relative; 元素设置 position: absolute; left: 50%; right: 50%; transform: translateX(-50%) translateY(-50%)
  3. table-cell + text-align + vetrical-align: 给父元素设置display:table-cell; text-align: center; vetrical: middle;
  4. flex: 父元素设置display: flex; justify-content: center; align-items: center;
  5. grid: 父元素设置display: flex;,元素设置:justify-self: center; align-self: center;

定宽高元素

  1. absolute + margin:父元素设置:position: relative; 元素设置 position: absolute; left: 50%; right: 50%; height: xpx; width: ypx; margin: -x/2px 0 0 -y/2px
  2. absolute + margin auto: 父元素设置:position: relative; 元素设置 position: absolute; left:0; right: 0;top: 0; bottom: 0; height: xpx; width: ypx; margin: auto
  3. absolute + calc: 父元素设置:position: relative; 元素设置 position: absolute; left:calc(50% - y/2px); top: calc(50% - x/2px); height: xpx; width: ypx;