CSS基础 水平居中案例

html结构
   <body>
        <div class="father">
              <div class="son"></div>
        </div>
   </body>

CSS结构
      <style>
        .father{
            position: relative;
            width: 400px;
            height: 300px;
            background-color: pink;
        }
        .son{
            position: absolute;
            top:0;
            left: 50%; /*相对父元素的50% ,margin-left同理*/
            transform: translateX(-50%); /*相对自己宽度回走50%*/
            width: 100px;
            height: 50px;
            background-color: blue;
        }
    </style>

这样无论是父盒子还是子盒子增大或者缩小,子盒子都是居中的

 

posted @ 2021-12-29 22:06  嘉琦  阅读(28)  评论(0)    收藏  举报