wolichuang / dailyInterview

面试、工作中遇到的issue
0 stars 0 forks source link

CSS 的居中方案有哪些? #12

Open wolichuang opened 3 years ago

wolichuang commented 3 years ago

水平居中

内联元素

  1. 使用 text-align:center
  2. 使用 Flexbox :display: flex; justify-content: center;
  3. 使用 Grid :display: grid; justify-content: center;

块元素

  1. 单个块元素使用 Auto Margin : margin: 0 auto;
  2. 单个块元素使用 display: flex; justify-content: center;
  3. 单个块元素transform使用 position: absolute; left: 50%; transform: translateX(-50%);
  4. 单个块元素已知宽度下使用 position: absolute;left: 50%;margin-left: -60px;
  5. 多个块元素父级使用 display: flex; margin-left: auto;margin-right: auto;

垂直居中

  1. Vertical Padding 使用 padding-top:20px; padding-bottom:20px;
  2. middle 使用 vertical-align: middle;
  3. Flexbox 使用 display: flex;justify-content: center;align-items: center;
  4. 绝对定位 使用 position: absolute;top: 50%;transform: translateY(-50%);
  5. 绝对定位 已知高度下使用 position: absolute;top: 50%;margin-top: -60px;
  6. Grid 使用 display: grid;align-items: center;

水平垂直居中

  1. Padding 和Text Align 使用 text-align: center; padding-top: 24px; padding-bottom: 24px;
  2. 绝对定位 使用 position: absolute;left: 50%;top: 50%;transform: translate(-50%,-50%);
  3. Flexbox 使用 display: flex;justify-content: center; align-items: center;
  4. Grid 使用 display: grid;justify-content: center;align-items: center;