css水平居中布局总结

2021-05-04  本文已影响0人  miao8862

水平居中

1. 子元素margin: 0 auto

父子元素的宽度皆已定,子元素的margin设为左右自动,margin: 0 auto;

    .father {
      background: yellow;
    }
    .son {
      margin: 0 auto;
      width: 50px;
      height: 40px;
      background: red;
    }

2. 父元素text-alight:center,子元素inline-block

父子元素宽度皆已定,父元素text-alight:center,子元素disploy: inline-block

3. grid布局

父元素display:grid; justify-content: center;

4. flex布局

父元素display:flex; justify-content: center;

水平和垂直居中

1. 绝对定位+margin(1)

子元素相对父元素绝对定位topleft都设为50%margin-leftmargin-top分别设为负的子元素的宽和高

    .father {
      width: 500px;
      height: 500px;
      position: relative;
      background: yellow;  
    }
    .son {
      position: absolute;
      top: 50%;
      left: 50%;
      margin-top: -20px;
      margin-left: -25px;
      width: 50px;
      height: 40px;
      background: red;
    }

2. 绝对定位+margin(2)

子元素相对父元素绝对定位,上下左右,right, bottom, topleft都设为0margin设为auto

3. 定位+transform

4. grid布局

父元素grid布局,align-items:center; justify-content: center;

    .father {
      display: grid;
      align-items: center;
      justify-content: center;
      width: 500px;
      height: 500px;
    }

5. flex布局

类似grid,只是使用flex布局,align-items:center; justify-content: center;

    .father {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 500px;
      height: 500px;
    }

6. 表格定位

父元素table表格布局,子元素设为单元格display: table-cell; vertical-align: center;text-align:center;

    .father {
      display: table;
      width: 500px;
      height: 500px;
      background: yellow;
    }
    .son {
      /* width, height无效 */
      width: 50px;  
      height: 40px;
      display: table-cell;
      text-align: center;
      vertical-align: middle;
      /* background: red; */
    }
上一篇 下一篇

猜你喜欢

热点阅读