position 分层固定在屏幕某位置

很多网站我们看到在屏幕右下角有一个,返回顶部,始终在那儿,还有些网站顶部菜单栏永远也是固定的不动,就是通过今天学习的position来做的。

在style中加入 positon:fixed;top 0;left 0;right 0;就是固定在顶部

<body>
<div onclick="Top();" style="height: 30px; 30px;background: #396764;color: white;
position: fixed;bottom: 0;right: 0;
margin-bottom: 20px;margin-right: 20px;
">top</div>
<div style="height: 3000px;background: #dddddd;">body</div>
<script>
    function Top() {
        document.documentElement.scrollTop = 0;
    }
</script>
</body>

  position 还有两个取值经常配合在一起用,relative,absolute.单独定义一个relative,是没有任何意义的,跟没定义一样。

  relative放在父标签中,它的子标签中才用absolute。作用是子标签的位置是相对于父标签来说的

<div style=" 500px;height: 200px;border: 1px solid red;margin: 0 auto; position: relative;">
    <div style="position: absolute;top: 0;left: 0; 30px;height: 30px;background: #000;"></div>
    <div style="position: absolute;top: 0;right: 0; 30px;height: 30px;background: #000;"></div>

    <div style=" 200px;height: 100px;border: 1px solid blue;margin: 0 auto;position: relative;">
        <div style="position: absolute;top: 50px;left: 100px; 30px;height: 30px;background: #750e60;"></div>
    </div>
</div>

<div style=" 500px;height: 200px;border: 1px solid red;margin: 0 auto; position: relative;">
    <div style="position: absolute;bottom: -30px;right: -30px; 30px;height: 30px;background: #000;"></div>
</div>

  

原文地址:https://www.cnblogs.com/alex-hrg/p/9365358.html