CSS水平垂直居中

1.利用定位(Position)

<!doctype html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style>
        *{
            margin:0;
            padding:0;
        }
        .parent{
            width:500px;
            height:500px;
            background: red;
            position: relative;
        }
        .child{
            width:50px;
            height:50px;
            background: yellow;
            position:absolute;
            left:50%;
            top:50%;
            margin-top:-25px;
            margin-left:-25px;
        }
    </style>
</head>
<body>
<div class="parent">
    <div class="child"></div>
</div>
</body>
</html

2.定位(position)与位移(translate)

//html
  <div class="parent">
      <div class="child">
      </div>
  </div>
//css
   .parent{
            width:300px;
            height:300px;
            background-color: red;
            position: relative;
        }
        .child{
            width:100px;
            height:100px;
            background-color: pink;
            position:absolute;
            left:50%;
            top:50%;
            transform: translate(-50%,-50%);
        }

3.定位

 //HTML
     <div class="one">
         <div class="two">
         </div>
     </div>
 //css
      .one{
            width:400px;
            height:400px;
            background-color: red;
            position: relative;
           }
        .two{
            width:100px;
            height:100px;
            background-color: pink;
            position: absolute;
            margin:auto;
            left:0;
            top:0;
            bottom:0;
            right:0;

        }

4.flex弹性布局

//html
  <div class="parent">
      <div class="child">
      </div>
  </div>
//css
   .parent{
            display: flex;
            justify-content: center;
            align-items: center;
            width:300px;
            height:300px;
            background-color: red;
        }
        .child{
            width:100px;
            height:100px;
            background-color: pink;
        }

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容