盒子的水平垂直居中

129 阅读1分钟

盒子的水平垂直居中

今天给大家带点干货,这是我在学css中遇到的问题,经过这么长时间的学习,在我们码代码的时候会遇到盒子水平垂直居中的问题,特别是学习的知识一多,各种各样的方法让人呢,眼花缭乱,这是我给大家总结的几种

note1

运用最初所学的文本知识来是盒子的元素

<style>
.box {
      width: 200px;
      height: 200px;
      margin: auto;
      line-height: 200px;
    }
</style>

note2

运用定位,用外边框margin的属性来是中间的盒子居中

.box {
      width: 200px;
      height: 200px;
      }
.san {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      width: 50px;
      height: 50px;
      background-color: skyblue;
      margin: auto;
      }

note3

也是运用定位,不过在同时运用transform:translate来该变盒子自己的位置来实现子盒子的居中

 .san {
      position: absolute;
      top: 50%;
      left: 50%;
      width: 50px;
      height: 50px;
      background-color: skyblue;
      transform: translate(-50%, -50%);
    }

note4

最后一个是手艺人用的-用margin扣出水平垂直居中的位置,具体的代码就不给出了,大家脑补


补充一下运用flex的弹性盒子居中的方法
 .san {
     display: flex;
     justify-content: center;
     align-items: center;
   }

注:我会随时根据我的学习的知识对盒子的水平垂直居中的方法进行总结,未完待续...