CSS之position浅谈

——部分转译自MDN;
position 常见的有static,relative, absolute, fixed几种。sticky不常见,我们放在最后说。
先粗暴的上段代码

<!DOCTYPE html>
<html>
    <head>
    <meta charset="utf-8">
    <script src="static/js/jquery.js"></script>
    <title>
    </title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        .wrapper {
            margin-top: 100px;
            width: 80%;
            border: 3px solid #ccc;
            margin: 100px auto;
        }
        .absolute, .static, .fixed, .relative {
            width: 200px;
            height: 200px;
            line-height: 200px;
            text-align: center;
        }
        .container {
            position: relative;
            margin-top: 100px;
            width: 80%;
            margin-left: 10%;
            height: 400px;
            border: 2px solid #ddd;
        }
        .absolute {
            position: absolute;
            background-color: green;
            top: 0px;
            left: 0px;
        }
        .static {
            position: static;
            background-color: pink;
            left: 100px;
            top: 100px;
        }
        .fixed {
            position: fixed;
            background-color: yellow;
            top: 0;
            left: 0;
        }
        .relative {
            position: relative;
            top: 0px;
            left: 0px;
            background-color: #aA1A00;
        }
    </style>
    </head>
    <body>
        <div class="wrapper">
            <div class="container">
                <div class="absolute">absolute 定位</div>
                <div class="fixed">fixed定位</div>
                <div class="static">static 定位</div>
                <div class="relative">relative 定位</div>
            </div>
        </div>
    </body>
</html>

样式如下

  • static

    默认的位置,不受left、right、top、bottom、index(对于index的忽略处理还是不太明白,有待解决)的影响。
    意思就是说设置了static的元素以默认的
    文档流的位置出现,即使对它设置了left、right、top、bottom、index也不会对它所处的位置造成影响。 参照前面的代码

   .static {
            position: static;
            background-color: pink;
            left: 100px;
            top: 100px;
        } 

我们对static设置的left, top丝毫不起作用。所以如果你的样式中对某个元素设置了static,就不要再费力的设置它的left等等了。
———-

  • relative

relative设置的是相对于它在文本流中默认的位置,进行定位。举例来说:
-当不对它的position进行任何操作
-当设置它的position: relative; left: 0; top: 0;两者是等义的。
设置了relative后,仍保留它在文本流中默认的位置,由此可见relative是个特别霸道的属性。,这就是所谓的占着茅坑不拉翔吧。这点absolute, fixed就比它强多了。

----------
  • absolute


  • fixed


  • sticky


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值