当我们给元素添加定位属性的时候,就可以控制元素在页面中的位置。
定位要搭配 left/right top/bottom 属性来使用

绝对定位absolute

<div class="demo"></div>

  1. .demo{
  2. width: 100px;
  3. height: 100px;
  4. background-color: red;
  5. position: absolute;
  6. left: 100px;
  7. top: 100px;
  8. }

显示效果
image.png
left:100px, top:100px的意思是左边线距离外部100px, 上变现距离外部100px.。 right跟bottom则是右边线跟底边线与外部的距离

现在我们来分析绝对定位的特点。看下面这个例子

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="../css/index.css" type="text/css">
</head>
<body>
    <div class="demo"></div>
    <div class="box"></div>
</body>
</html>
.demo{
    width: 100px;
    height: 100px;
    background-color: red;
    opacity: 0.5;
}

.box{
    width: 150px;
    height: 150px;
    background-color: green;
}

显示效果
image.png现在这有两个盒子代码如上。我们试试给demo这个盒子加上绝对定位属性看看效果。

.demo{
    width: 100px;
    height: 100px;
    background-color: red;
    opacity: 0.5;
    position: absolute;
    left: 0;
    top: 0;
}

image.png我们发现两个盒子叠在一起了。这是什么情况?

相对定位relative

还是demo跟box这两个盒子,这次我们用相对定位来看看有什么不一样

.demo{
    width: 100px;
    height: 100px;
    background-color: red;
    opacity: 0.5;
    position: relative;
    left: 100px;
    top: 100px;
}

.box{
    width: 150px;
    height: 150px;
    background-color: green;
}

image.png我们发现box这次没有顶上去,这又是为什么?

再看一个例子

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="../css/index.css" type="text/css">
</head>
<body>
    <div class="wrapper">
        <div class="content">
            <div class="box"></div>
        </div>
    </div>
</body>
</html>
.wrapper{
    width: 200px;
    height: 200px;
    background-color: orange;
    margin-left: 100px;
}


.content{
    width: 100px;
    height: 100px;
    background-color: red;
    margin-left: 100px;

}

.box{
    width: 50px;
    height: 50px;
    background-color: green;
}

image.png
三个盒子。 现在我们给最里面的box盒子加上绝对定位属性

.box{
    width: 50px;
    height: 50px;
    background-color: green;
    position: absolute;
    left: 50px;
}

image.png
我们发现绿色小方块跑到外面来了。现在我们给红色的盒子加上相对定位属性

.content{
    width: 100px;
    height: 100px;
    background-color: red;
    margin-left: 100px;
    position: relative;

}

image.png
我们发现原来的绿色方块的位置改变了。

现在我们来总结相对定位,绝对定位的规律

absolute绝对定位

  1. 脱离原来的位置进行定位
  2. 相对于最近的有定位的父级进行定位,如果没有相对于文档进行定位

    relative相对定位

  3. 保留原来的位置进行定位

  4. 相对于自己原来的位置进行定位

固定定位fixed

固定定位比较简单,我们给元素添加定位属性postion:fixed
那么元素就会固定在屏幕的某个位置上,无论我们屏幕如何滚动它都不会动