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

绝对定位

居中布局通常分为两种,一种是固定宽高,另一种是非固定宽高。

固定宽高很好理解,非固定宽高通常都是靠里面的来撑起盒子的高度,时多时少。

这两种方式也造就了不一样的技术实现,我们来看一下。

假如我们有宽度占 70%,高度占 25% 的盒子,我们可以这么写:

<!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;

      /* 上下左右全部为0 */
      top: ;
      right: ;
      bottom: ;
      left: ;

      /* 给定宽高 */
      width: ;
      height: ;

      /* 令外边距填充 */
      margin: auto;

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

运行结果:

学会了绝对定位来进行居中之后,下一小节我们再来看一下绝对定位怎么和外边距进行搭配。


联系我
置顶