前端那些事

vuePress-theme-reco chenpeng    2020 - 2021
前端那些事 前端那些事

Choose mode

  • dark
  • auto
  • light
首页
文章目录
  • Browser
  • CSS
  • ES6
  • JavaScript
  • Network
  • TypeScript
  • Vue
  • Vue3
  • Webpack
标签
时间轴
GitHub
author-avatar

chenpeng

85

Article

25

Tag

首页
文章目录
  • Browser
  • CSS
  • ES6
  • JavaScript
  • Network
  • TypeScript
  • Vue
  • Vue3
  • Webpack
标签
时间轴
GitHub
  • CSS

    • CSS Modules
    • CSS层叠上下文
    • CSS中的伪类与伪元素
    • CSS水平垂直居中
    • CSS两栏布局和三栏布局
    • CSS - BFC
    • link与@import的区别
    • CSS动画相关属性
    • CSS - flex

CSS水平垂直居中

vuePress-theme-reco chenpeng    2020 - 2021

CSS水平垂直居中

chenpeng 2020-04-30 CSS

# 1、利用定位和 transform 属性实现

<style>
    .parent{
        width: 500px;
        height: 500px;
        background-color: cornflowerblue;
        position: relative;
    }
    .child{
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
    }
</style>
1
2
3
4
5
6
7
8
9
10
11
12
13
14

IE9 以下不支持 transform

# 2、利用 flex 布局实现

<style>
    .parent{
        width: 500px;
        height: 500px;
        background-color: cornflowerblue;
        display: flex;
        justify-content: center;
        align-items: center;
    }
    .child{
        background-color: red;
    }
</style>
1
2
3
4
5
6
7
8
9
10
11
12
13

兼容性不好,很多浏览器都不支持

# 3、利用 table 布局实现

<style>
    .parent{
        width: 500px;
        height: 500px;
        background-color: cornflowerblue;
        display: table;
    }
    .child{
        display: table-cell;
        text-align: center;
        vertical-align: middle;
    }
</style>
1
2
3
4
5
6
7
8
9
10
11
12
13

IE8 以下不支持