您的当前位置:首页正文

深入理解CSS之absolute

来源:要发发知识网

1. absolute 的包裹性和破坏性

1.1 包裹性

假设有一段html:

<div class="box">
        
</div>

css 为:

.box{
    padding: 10px;
    background-color: #f0f0f0;
 }

此时结果为:

此时box没有定位

当给 box 添加绝对定位的 css:

.box{
      position:absolute;
}

结果为:

box 绝对定位

1.2 破坏性

1. 还是子元素和父元素均未定义时的结果:
此时box 和 img 没有定位
2. 给 img 元素设置绝对定位,可以看出绝对定位具有破坏性。
img {
      position:absolute;
}
父容器塌陷了

2. 绝对定位的跟随性,单独使用功能更强大

通常使用绝对定位时,是把绝对定位和相对定位结合使用,让父元素使用相对定位,子元素相对于父元素绝对定位。但是,绝对定位单独使用有更强大的功能。

2.1 独立的 absolue 可以摆脱 overflow 的限制,无论是滚动还是隐藏

如下面一段代码:

<style type="text/css">
    .container{
        width: 200px;
        height: 200px;
        background-color: #f0f0f0;
        overflow: scroll;
    }
    .test{
        margin-left: 100px;
    }
</style>
<body>
    <div class="container">
        <div class="test">testContanttestingtesting</div>
        
        
        
    </div>
</body>

父容器设置 overflow: scroll; 观察 class = 'test' 的情况:

正常情况下是这样的

给 测试 div 添加绝对定位。它便脱离文档流,不受父容器 overflow 的影响:

无论父容器 hidden 还是 scroll,测试div就在那,不倚不正

2.2 去浮动:absolute 和 float 同时出现时,absolute 起作用。

2.3 跟随性:设置绝对定位的元素,会跟随它之前的元素。

比如这个元素是 display:block;设置绝对定位之后,它仍以 display:block 的形式跟随在前一个元素后面,不过是脱离文档流的。 同样,如果这个元素是 display: inline-block, 设置绝对定位之后,同样以它原来的形式跟在前一个元素后面。(在 Chrome 浏览器中,一个元素一旦设置了绝对定位,再修改它的 display 不起作用。)

如下代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style type="text/css">
        .box1,.box2,.box3{
            width: 100px;
            height: 100px;
            display: inline-block;
        }
        .box1{
            background-color: red;
        }
        .box2{
            background-color: green;
        }
        .box3{
            width: 150px;
            background-color: orange;
        }
    </style>
</head>
<body>
    <div class="box1">box1</div>
    <div class="box2">box2</div>
    <div class="box3">box3</div>
</body>
</html>

结果为:

没有定位时的结果
然后在 .box2 的 div 上做文章。
1. 给 box2 设置绝对定位
box2 脱离文档流,因为原来是 inline-block,仍以 inline-block 跟随在前一个元素后面
2. 给box2 设置绝对定位和 display:block

首先设置 display:block:

box2 未设置绝对定位时

然后设置绝对定位:

box2 设置绝对定位

3. 绝对定位下的元素,left:0,right:0,同时存在。

.box{
  position: absolute;
  width: 100px;
  height: 100px;
  background: #f0f0f0;
  left: 0;
  right: 0;
}
<div class="box">
    this is abso
</div>
位于浏览器左上角
** 如果给上述box元素添加margin:auto,元素会居中。就是因为有left:0; right:0.**

4.没有宽度和高度声明实现的全屏自适应效果

// 方法一
 .box {
  position: absolute;
  left: 0; top: 0; right: 0; bottom: 0;
}

// 方法二
html,body{
  height:100%;
}
.box{
  position:absolue;
  width:100%;
  height:100%;
  left:0;
  top:0;
}
使用场景 IE8 以上支持

5. 绝对定位布局的使用

如果不设置`html,body{height:100%}` 子元素高度仍然为0 (未验证)