CSS 水平/竖直居中小集合

2018-11-16  本文已影响8人  Kerwin_F

平常前端开发的时候经常遇到这样的问题,时不时就会忘记,今天就想一次性把所有 CSS居中 的方法进行总结,当做自己的备忘录

一、水平居中

概括:

  1. 内联元素 text-align:center
  2. 块级元素 margin: 0px autp;
  3. 多块级元素,将块级元素设置为 inline-block,再通过 text-align
  4. flex 布局 justify-content: center

二、垂直居中

概括:

1.单行元素:heightline-height 设置一样的高度

  1. table 布局,父元素设置 display: table ,子元素设置 display: table-cell; vertical-align: center
  2. flex 布局 align-center:center
  3. CSS3 transform 属性,结合绝对位置,实现垂直居中,部分浏览器会有兼容性问题
.parent {
    position: relative;
}
.child {
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
}

三、水平+垂直 布局

  1. flex 双重属性设置居中
  2. table + 设置宽度+ margin 来完成(兼容性有较好的的保证)
  3. 未知宽高元素,通过 transform + absolute
.parent {
    position: relative;
}
.child {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}
  1. 固定宽高——通过设置 absolutemargin 反向设置进行
  2. grid 布局(不清楚后期补)

以下是上方部分的详细例子


二、垂直居中

1. 单行内联元素垂直居中

<style>
  .main{
    height: 200px;
    background-color: #fcc;
    overflow: hidden;
    line-height: 40px;
    font-size: 40px;
  }
</style>
<template>
  <div class="main">
      我是一行
  </div>
</template>
line-height、height 配合单行垂直居中

通过 height line-height 配合进行垂直居中

line-height 属性设置行间的距离(不允许为负值)

这个距离是两行之间基线的举例,看下图会很清楚

image.png

定义height 的五种方式:

1.line-height可以被定义为:body{line-height:normal;}

2.line-height可以被定义为:body{line-height:inherit;}

3.line-height可以使用一个百分比的值body{line-height:120%;}

4.line-height可以被定义为一个长度值(px,em等) body{line-height:25px;}

5.line-height也可以被定义为纯数字, body{line-height:1.2}—————会通过font-size 自动进行调节

更详细的例子在这里查看 深入了解css的行高Line Height属性

2.多行垂直居中

<style>
  .table{
    display: table;
    background-color: #4cd1d4;
    height: 150px;
  }
  .cell{
    display: table-cell;
    vertical-align: middle;
  }
</style>
<template>
    <div class="table">
      <div class="cell">
        我是一行
        <br>
        我是二行
      </div>
    </div>
</template>
table 多行垂直居中

3. Flex 布局

通过设置 flex 布局的交叉轴方向即可 align-items: center

<style>
  .flexStyle{
    display: flex;
    align-items: center;
    height: 100px;
    background-color: gray;
  }
</style>
<template>
  <div class="flexStyle">
    flex 布局
  </div>
</template>
image.png

三、水平垂直居中

1. 未知宽高元素水平垂直居中

利用 2D 变换

.parent {
    position: relative;
}
.child {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

利用 flex 布局

设置 主轴方向 justify-content 和 交叉轴方向 align-center (也就是纵轴)为 center 就可以达到居中

table布局

结合开始 table 垂直居中,外层设置 display:table,内层设置 display: table-cell;vertical: center,最后在通过水平垂直的方法完成

引用参考

CSS line-height概念与举例
深入了解css的行高Line Height属性
这15种CSS居中的方式,你都用过哪几种?

上一篇 下一篇

猜你喜欢

热点阅读