美文网首页
relative和absolute详解

relative和absolute详解

作者: 苹果咏 | 来源:发表于2020-11-17 11:47 被阅读0次

    结论:relative(相对定位)是相对于自己目前所在的位置进行定位,元素还是处于文档流当中。
    absolute(绝对定位)是相对于离它最近的且不是static定位的父元素进行定位,而且元素脱离文档流,它原本的位置就是空的,后面的元素会上来补空位。

        <div class="container clearfix">
            <div class="box">
    
            </div>
        </div>
    
        <div class="container1 clearfix">
            <div class="box1">
    
            </div>
        </div>
    
            .container{
                width: 500px;
                height: 300px;
                border: 1px solid red; 
                position: relative;
                top: 100px;
                left: 100px; 
            }
            .box{
                width: 100px;
                height: 100px;
                border: 1px solid black;
                position: absolute;
                top:50px;
                left: 50px;
            }
    
            .container1{
                width: 500px;
                height: 300px;
                border: 1px solid red;
                background-color: aquamarine;
                position: relative;
                
            }
            .box1{
                width: 100px;
                height: 100px;
                border: 1px solid black;
                position: absolute;
                top:50px;
                left: 50px;
            }
    
    image.png

    第一个box设relative相对于自己的位置向下、向右偏移100px,此操作会与下面的box重叠
    里面的小box设absolute相对于大box进行定位,前提是大box已经有非static定位,否则会相对于html进行定位

    如果我们把container,也就是大box的position删掉,此时的小box相对根元素html进行定位,效果是这样:


    为了能看出区别,我给大box加了100margin

    以前的误区:之前认为一个元素要相对于父级元素进行绝对定位,父元素设relative,子元素设absolute才行。其实不是,只要父元素有非static定位即可。

    若父元素和子元素都设absolute,则父元素相对于html定位,子元素相对于父元素定位。

    参考:https://blog.csdn.net/weixin_42067967/article/details/80152403

    相关文章

      网友评论

          本文标题:relative和absolute详解

          本文链接:https://www.haomeiwen.com/subject/nxkxiktx.html