图解CSS中的position:static、fixed、relative、absolute

342 阅读2分钟

就像茴香的茴字有四种写法一样,CSS中需要掌握的position也有4种
为了方便学习,我们首先需要构建一个基本布局,与position不相关的css直接放在了html中:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="style.css">
    <style>


        body{
            font-family: "Arial","宋体",sans-serif;
            font-weight: bold;
            font-size: 200%;
        }
        .parent{
            background-color: lightblue;
            height: 400px;
            padding: 50px;
        }
        .child-one{
            background-color: lightcoral;
        }.child-two{
            background-color: lightgoldenrodyellow;
        }.child-three{
            background-color: lightgray;
        }.child-four{
            background-color: lightpink;
        }

    </style>
</head>
<body>
    <div class="parent">
        天净沙.秋思
        <div class="child-one">枯藤老树昏鸦</div>
        <div class="child-two">小桥流水人家</div>
        <div class="child-three">古道西风瘦马</div>
        <div class="child-four">夕阳西下,断肠人在天涯</div>

    </div>

</body>
</html>

1.static

在我们什么都没干的时候,默认的position是static,我们可以按F12查看: image.png

天净沙是父元素,四句诗是平行的兄弟元素,效果是这样的: image.png

2.relative

接下来,我们把第二句加上relative: image.png

.child-one{
    position: relative;
}

和上图看起来毫无变化,这是因为relative position的效果和static position很相似。但设置为relative之后你可以比static多出四项能力:改变top、left、right、bottom。

image.png

.child-two{
    position: relative;
    top: 20px;
}

image.png

.child-two{
    position: relative;
    top: 20px;
    left: 30px;
}

你会发现这么设置之后小桥流水人家,就脱离了整句诗天净沙的范围,它就像浮空了一样(overflow parent class),这是因为relative允许你实际的改变元素的相对位置,也就是传说中的“脱离了文档流”,所以不建议使用在使用relative的时候设置宽高。

3.absolute

如果我们直接对第二句设置absolute:

image.png

.child-two{
    position: absolute;
}

我们会发现灰色那行的字直接消失了,而背景颜色有一半到了“小桥流水人家”的位置。这是因为absolute把设置的那一行完全脱离了文档流,其他元素根本看不见也摸不着它,以为那里没有东西,按正常状态布局,其实灰色的那行就在黄色那行下面,它确实被浏览器渲染出来了,只是你没有看到罢了。

让我们把它移动到最上方:

image.png

.child-two{
    position: absolute;
    top: 0;
}

这样,无论我们下方如何改变,它都会稳定在最上方,可以用来做导航栏。要注意的是,如果我们把页面拉长到需要滚动的程度,absolute是会被遮盖的。

image.png

.parent{
    height: 200vh;
}

4.fixed

而如果我们用的是fixed,在单页面下和absolute是很相似的:

image.png

.child-two{
    position: fixed;
    top: 0;
}

但是如果我们向下滑动窗口,你会发现他还是在这:

image.png

image.png

image.png 是不是明白有些网页的小广告是怎么做的了?

image.png