盒子水平和垂直居中的方法

1.利用定位position和transform

    *{
     
      padding: 0;
      margin: 0;
    }
    html,body{
     
      width: 100%;
      height: 100%;
    }
    .father{
     
      height: 100%;
      width: 100%;
      background-color: red;
    }
    .son{
     
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%,-50%);
      width: 200px;
      height: 200px;
      background-color: skyblue;
    }
html部分
  <div class="father">
    <div class="son">
    </div>
  </div>

盒子水平和垂直居中的方法_第1张图片

2.或者利用margin-top 负的自身的一半

此时需要知道盒子的大小
利用相对定位使自身偏移父盒子大小的一般,然后利用margin-top或margin-left的负值将自身再平移回去。

    .father{
     
      height: 100%;
      width: 100%;
      background-color: red;
    }
    .son{
     
      position: absolute;
      left: 50%;
      top: 50%;
      margin-top: -100px
      width: 200px;
      height: 200px;
      background-color: skyblue;
    }

3.利用弹性盒子flex属性

通过对父盒子定义flex,使子元素为伸缩盒子,再利用
align-itema:center; 使得元素垂直居中
justify-conter:ceneter; 使得盒子中的元素水平居中

    *{
     
      padding: 0;
      margin: 0;
    }
    html,body{
     
      width: 100%;
      height: 100%;
    }
    .father{
     
      height: 100%;
      width: 100%;
      background-color: red;
      display: flex;
      align-items: center;  /*定义子元素垂直居中 */
      justify-content: center;  /*定义子元素水平居中 */
    }
    .son{
     
      width: 200px;
      height: 200px;
      background-color: skyblue;
    }

最后使用css书写顺序的规范

1.位置属性(position, top, right, z-index, display, float等)

2.大小(width, height, padding, margin)

3.文字系列(font, line-height, letter-spacing, color- text-align等)

4.背景(background, border等)

5.其他(animation, transition等)

你可能感兴趣的:(c,s,s,css)