23-盒子水平垂直居中技巧

86 阅读1分钟

盒子水平垂直居中

使用margincalc()配合计算

  • margin-top: calc((100% - 小盒子高度) / 2);

  • margin-left: calc((100% - 小盒子宽度) / 2);

    • 注意:当前方法只适用于大盒子宽高一致时,因为100%默认都是参考大盒子的宽度

适用定位和偏移量配合计算

  • 大盒子设置相对定位,小盒子设置绝对定位

  • 给小盒子设置偏移量

    • top: calc((100% - 小盒子高度) / 2);

    • left: calc((100% - 小盒子宽度) / 2);

      100%可以分别参考大盒子的宽和高,也就是大盒子宽高不一致时也适用

margin配合定位自适应

  • 大盒子设置相对定位,小盒子设置绝对定位

  • 给小盒子设置偏移量

    • top:0
    • bottom:0
    • left:0
    • right:0
  • 小盒子进行margin自适应

    • margin:auto
1.  `<style>`
1.  `.outer{`
1.  `width: 500px;`
1.  `height: 700px;`
1.  `border: 1px solid red;`
1.  `/* 相对定位 */`
1.  `position: relative;`
1.  `}`
1.  `.inner{`
1.  `width: 200px;`
1.  `height: 200px;`
1.  `background-color: pink;`
1.  `/* 绝对定位 */`
1.  `position: absolute;`
1.  `/* 偏移量设置 */`
1.  `left: 0;`
1.  `right: 0;`
1.  `top: 0;`
1.  `bottom: 0;`
1.  `/* margin自适应 */`
1.  `margin: auto;`
1.  `}`
1.  `</style>`
1.  `<body>`
1.  `<div class="outer">`
1.  `<div class="inner"></div>`
1.  `</div>`
1.  `</body>`