前端面试题库

常见的水平垂直居中实现方案

flex更新时间:2024-08-23 07:53:33

答案

  1. flex布局,或者grid

    .parent { display: flex/grid; justify-content: center; align-items: center; } .child { ... }
  2. 绝对定位配合margin:auto

    .parent { position: relative; } .child { position: absolute; top: 0; left: 0; bottom: 0; right: 0; margin: auto; }
  3. 绝对定位配合transform实现

    .parent { position: relative; } .child { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); }

评论