前端css基础,使得子盒子垂直水平居中的4种基础方法

92 阅读1分钟

css基础实现简单的盒子布局垂直和水平居中的方法,代码内有简单的注释

一,运用定位(子绝父相)

<style>
    .one {
      /* 父相 */
      position: relative;
      width: 600px;
      height: 400px;
      background-color: #ccc;
    }
    .two {
      /* 子绝 */
      position: absolute;
      width: 100px;
      height: 100px;
      background-color: red;
      /* 相右和下走父元素的一半 */
      left: 50%;
      top: 50%;
      /* 移动自身的宽高一半 */
      margin-left: -50px;
      margin-top: -50px;
    }
  </style>

二,2d平面位移实现居中(translate:translate(x,y)

<style>
    .one {
      /* 父相 */
      position: relative;
      width: 600px;
      height: 400px;
      background-color: #ccc;
    }
 
    .two {
      /* 子绝 */
      position: absolute;
      width: 100px;
      height: 100px;
      background-color: red;
      /* 相右和下走父元素的一半 */
      left: 50%;
      top: 50%;
      /* 移动自身的宽高一半 */
      transform: translate(-50%, -50%);
    }
  </style>
 
</head>
 
<body>
  <div class="one">
    <div class="two"></div>
  </div>
</body>

三,小技巧(子元素必须有宽高)

<style>
    .one {
      /* 父相 */
      position: relative;
      width: 600px;
      height: 400px;
      background-color: #ccc;
    }
 
    .two {
      /* 子绝 */
      position: absolute;
      width: 100px;
      height: 100px;
      background-color: red;
      /* 上下左右定位0,加margin:auto; */
      left: 0;
      right: 0;
      top: 0;
      bottom: 0;
      margin: auto;
    }
  </style>
 
</head>
 
<body>
  <div class="one">
    <div class="two"></div>
  </div>
</body>

四,flex布局

<style>
        .father {
            width: 400px;
            height: 400px;
            background-color: pink;
           
            display: flex;
            justify-content: center;
            align-items: center;
        }
        .father .son {
            width: 100px;
            height: 100px;
            background-color: blue;
        }
    </style>
</head>
<body>
    <div class="father">
        <div class="son"></div>
    </div>
</body>