使用flex布局实现水平垂直居中效果

1,705 阅读1分钟

1、给父盒子开启flex布局

display: flex;

2、在父盒子中设置justify-content属性,实现水平居中

justify-content: center;

3、在父盒子中设置align-items属性,实现垂直居中

align-items: center;

4、完整代码:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <style>
    * {
      margin0;
      padding0;
    }
    .box {
      width600px;
      height80px;
      background-color#f40;
      margin50px auto;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  </style>
</head>
<body>
  <div class="box">
    <p>flex布局1</p>
    <p>flex布局2</p>
  </div>
</body>
</html>

5、不设置flex布局和设置flex布局前后的对比如下:

不设置flex布局: image.png

设置flex布局:

image.png