Css定位属性position使用

Position有四个属性值用来确定定位方式分别是:static(静态定位,position默认值);absolute(绝对定位);relative(相对定位);fixed(固定定位);sticky(粘性定位)。

用法:

absolute(绝对定位)根据父元素定位使用 left right top bottom指定的坐标

</head>
    <style>
         *{
            margin:0;
            padding:0;
        }
        .box{
            width:400px;
            height:200px;
            background:red;
            margin:50px auto;
            /* 形成参照物 */
            position:absolute;
        }
        .box p{
            width: 200px;
            height:100px;
            background:yellow;
            /* 根据父元素的定位进行位置的变化 */
            position:absolute;
            left:20px;
            top:50px;
        }
    </style>
<body>
    <div class="box">
        <p>子元素</p>
    </d

relative(相对定位)根据自身的默认位置使用 left right top bottom指定的坐标且占据空间不会破话文档流。

   <style>
         *{
            margin:0;
            padding:0;
        }
        .box{
            width:400px;
            height:200px;
            background:red;
        }
        .box p{
            width: 200px;
            height:100px;
            background:yellow;
            /* 根据自身默认位置进行位置的变化 */
            position:relative;
            left:20px;
            top:60px;
        }
    </style>
<body>
    <div class="box">
        <p>子元素</p>
    </div>
</body>
</html>

fixed;(固定定位)参照浏览器窗调整位置,脱离整个文本流。

   <style>
         *{
            margin:0;
            padding:0;
        }
        .box{
            width:400px;
            height:200px;
            background:red;
        }
        .box p{
            width: 200px;
            height:100px;
            background:yellow;
            /* 根据浏览窗口进行位置的变化 */
            position:fixed;
            left:50%;
            top:100px;
        }
    </style>
<body>
    <div class="box">
        <p>子元素</p>
    </div>

Sticky(粘性定位)是relative和fixed的结合,在窗口内执行relative,超出按fixed执行。一般用于吸住顶部。

   <style>
         *{
            margin:0;
            padding:0;
        }
        .box{
            width:400px;
            height:200px;
            background:red;
        }
        .box_t{
            background:purple;
            }
        p{
            background:yellow;
            margin:0 auto;
            position:sticky;
            top:0;
        }
    </style>
<body>
    <div class="box"></div>
    <p>吸顶</p>
    <div class="box_t">
        <h2>12344</h2>
        <h2>12344</h2>
        <h2>12344</h2>
        <h2>12344</h2>
        <h2>12344</h2>
        <h2>12344</h2>
        <h2>12344</h2>
        <h2>12344</h2>

 2020-02-22

 

猜你喜欢

转载自www.cnblogs.com/ylyblogs/p/12344751.html