GBX

CSS定位(Position)

css提供了3种机制来设置盒子的摆放位置,分别是标准流浮动定位

定位:将盒子定在某一个位置,并且漂浮在其他盒子的上面

定位有4个属性值:

  • static(静态定位)

  • relative(相对定位)

  • absolute(绝对定位)

  • fixed(固定定位)

静态定位(static)

静态定位是元素的默认定位方式,无定位的意思

相对定位(relative)

相对定位是元素相对于它原来在标准流中的位置来发生位置改变

原来在标准流中的位置继续占有,后面的盒子不会受到影响

<style>
        * {
            margin: 0;
            padding: 0;
        }
        .box1 {
            width: 100px;
            height: 100px;
            background-color: pink;
        }
        .box2 {
            position: relative;
            left: 100px;
            top: 50px;
            width: 100px;
            height: 100px;
            background-color: yellowgreen;
        }
        .box3 {
            width: 100px;
            height: 100px;
            background-color: blueviolet;
        }
    </style>

  

绝对定位(absolute)

绝对定位是元素以带有定位的父元素来移动位置

  • 完全脱离标准流(完全不占位置)

  

<style>
        * {
            margin: 0;
            padding: 0;
        }
        .far {
            position: absolute;
            left: 0;
            top: 0;
            width: 50px;
            height: 50px;
            background-color: pink;
        }
        .son {
            width: 100px;
            height: 100px;
            background-color: royalblue;
        }
    </style>

  

  • 如果父元素没有定位,则以浏览器为准

  

<style>
        * {
            margin: 0;
            padding: 0;
        }
        .far {
            width: 100px;
            height: 100px;
            margin: 50px 50px;
            background-color: pink;
        }
        .son {
            position: absolute;
            left: 0;
            top: 0;
            width: 50px;
            height: 50px;
            background-color: royalblue;
        }
    </style>

 

  • 父元素有定位
    • 将元素依据最近的已经定位(绝对、固定或相对定位)的父元素进行定位

    

<style>
        * {
            margin: 0;
            padding: 0;
        }
        .far {
            position: relative;
            width: 100px;
            height: 100px;
            margin: 50px 50px;
            background-color: pink;
        }
        .son {
            position: absolute;
            left: 20px;
            top: 20px;
            width: 50px;
            height: 50px;
            background-color: royalblue;
        }
    </style>

固定定位(fixed)

  • 完全脱离标准流

  • 只认浏览器的可视窗口

  • 与父元素没有任何关系单独使用

  • 不随滚动条滚动

  

 <style>
        .box {
            position:fixed;
            right: 0;
            top: 0;
            width: 100px;
            height: 100px;
        }
</style>

 

粘性定位(sticky)

position:relative 和 position:fixed的结合

  • 如果页面没超出窗口范围,按照relative 执行

  • 如果内容超出窗口位置,按照fixed执行

  导航栏吸顶实现方法

​position:sticky;

top:0;

默认:导航条到窗口顶部时:

堆叠顺序(z-index)

在使用定位布局时,可能会出现盒子重叠的情况

加了定位的盒子,默认后来者居上, 后面的盒子会压住前面的盒子。

应用 z-index 层叠等级属性可以调整盒子的堆叠顺序

如图:

 

 

 

 

 

 

 

 

z-index 的特性如下:

  1. 属性值正整数负整数0,默认值是 0,数值越大,盒子越靠上;

  2. 如果属性值相同,则按照书写顺序,后来居上

  3. 数字后面不能加单位

  4. 注意 z-index是只能用于相对定位绝对定位固定定位的元素
posted on 2020-02-22 16:58  GBX  阅读(213)  评论(0)    收藏  举报