您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

绝对定位+平移

有时中间盒子的是要靠传过来的数据决定的,如果写死的话,当数据较多时就会发生溢出,数据较少时又会空出一大片,所以我们需要一种更加智能的方式来实现居中布局。

绝对定位 + 平移绝对定位 + 负边距的改进版,那么具体都改进了哪些方面呢?

负边距的百分比并不是相对于自身,而是相对于父元素,所以只能写具体的像素值,显得不够智能。

而平移相对于自身,只需要无脑写 -50% 就可以了。

来看如何用绝对定位+平移来实现居中布局:

<!DOCTYPE html>
<html>
<head>
  < charset="UTF-8">
  < name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    /* 清除认样式 */
    * { padding: ; margin: ; }

    /* 令html和body全屏, 并有灰色背景 */
    html, body { height: ; background: gray; }

    /* 先在父元素上设置相对定位 */
    body { position: relative }

    .center {
      /* 绝对定位 */
      position: absolute;

      /* 上方和左方为50% */
      top: ;
      left: ;

      /* 不用给宽高,但是可以给个内边距防止与盒子过于贴合 */
      padding: px;

      /* 这个50%是相对于自身宽高而言的 */
      transform: translate(-, -);

      /* 白色背景 */
      background: white;
    }
  </style>
</head>
<body>
  <div class="center">
    用撑开盒子
  </div>
</body>
</html>

运行结果:


联系我
置顶