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

绝对定位

无论什么布局几乎都可以使用绝对定位来实现,那为什么好多布局并不会首选绝对定位呢?

一方面是因为写起来可能有点麻烦,另一方面是因为必须得,那具体要怎么呢?

看来实现你就明白了。

<!DOCTYPE html>
<html lang="en">
<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; }

    div {
      /* 绝对定位 */
      position: absolute;

      /* 令其上下方向与父元素的距离为0 */
      top: ;
      bottom: ;

      /* 白色背景 */
      background: white;
    }

    /* 左边的列 */
    .left {
      /* 令其左侧方向与父元素的距离为2% */
      left: ;

      /* 令其右侧方向与父元素的距离为51% */
      right: ;
    }

    /* 右边的列 */
    .right {
      /* 令其左侧方向与父元素的距离为51% */
      left: ;

      /* 令其右侧方向与父元素的距离为2% */
      right: ;
    }
  </style>
</head>
<body>
  <div class="left"></div>
  <div class="right"></div>
</body>
</html>

运行结果:

这里加起来不等于 100%,因为这里的百分号指的不是宽度,而是相对于父元素的距离。

那这该怎么算呢?其实也简单,我们在屏幕正中央位置画一条线,这条线就代表距离左边 50%、距离右边也是 50%:

然后左边 2%、右边 2%、中间 2%,但是中 2% 被平分成了两个 1%,我们再画几条线看一下:

左边的红线代表 left: 2%;@H_510_@,右边的两条绿线加在一起就是 51%,代表 right: 51%@H_510_@;

其实就是一道简单的数学题,算好百分比就可以用绝对定位啦!


联系我
置顶