css中position定位及其注意点

position定位

1.相对定位 relative

特点:
  • 与标准文档流下的盒子没有任何区别
参考点选取:
  • 以自身原来位置为参考点

2.绝对定位 absolute

特点:

  • 脱离标准文档流
  • 层级提高,压盖效果
  • 布局方案 (子绝父相)

参考点选取:

  • 情况一:父级盒子没有定位

    • 单独设置一个盒子为绝对定位,参考点是body盒子为参考
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Document</title>
        <style>
         .box1,.box2,.box3{
             width:100px;
             height:100px;
             background-color: orange;
         }
         .box2{
            /* margin-top:30px; */
            background-color: aqua;
            position:absolute;
            top:0;
            left:0
            /* 祖先盒子都没有非static的定位设置 */
            /* box2 设置绝对定位相对于body */
         }
         .parent{
             width:400px;
             height:400px;
             border:1px solid red
         }
    
        </style>
    </head>
    <body>
        <div class="parent">
            <div class="box1">box1</div>
            <div class="box2">box2</div>
            <div class="box3">box3</div>
        </div>
    </body>
    </html>
    
    #top:相对body的顶部top位置20px像素处
    #left:相对body左边的10像素处
    #bottom:
    #right:
    
  • 情况二:祖先盒子有设置定位,相对于最近的非static祖先元素定位

    • 找最近的父级盒子的定位作为参考点
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Document</title>
        <style>
         .box1,.box2,.box3{
             width:100px;
             height:100px;
             background-color: orange;
         }
         .box2{
            /* margin-top:30px; */
            background-color: aqua;
            position:absolute;
            top:0;
            left:0
            /*  */
            /* box2 设置绝对定位相对于parent */
         }
         .parent{
             /* width:400px;
             height:400px; */
             border:1px solid red;
             position: relative;
         }
    
        </style>
    </head>
    <body>
        <div class="parent">
            <div class="box1">box1</div>
            <div class="box2">box2</div>
            <div class="box3">box3</div>
        </div>
    </body>
    </html>
    

3.固定定位

参考点:固定元素则是相对于浏览器视口本身

4.position的注意事项

注意:子绝父绝,子绝父固,都是以最近的非static父辈元素作为参考点。父绝子绝,子绝父固,没有实战意义,布局网站的时候不会出现父绝子绝。因为绝对定位脱离标准流,影响页面的布局。

父相子绝:

在我们页面布局中,是常用的布局方案。因为父亲设置相对定位,不脱离标准流,子元素设置绝对定位,仅仅的是在当前父辈元素内调整该元素的位置。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值