浅谈css position absolute相对于父元素的设置方式

浅谈css position absolute相对于父元素的设置方式,第1张

浅谈css position absolute相对于父元素的设置方式

大家知道css的position absolute默认是根据document来设置的,比如position:absolute后设置left:0;top:0这时候元素会显示到页面的左上角。


有时候我们需要在父元素的容器内设置相对的绝对位置

要做到这一点需要把父元素的position属性设置为relative,设置为relative之后不设置left和top属性,这时候父元素虽然是relative的,但是还是在原来位置。


然后把子元素的位置position设置为absolute的,并设置其left,top,right,bottom属性,这样就是相对于父元素的绝对位置了。


如下html示例代码:

<!doctype html>
<html>
    <style type="text/css">
    #father {
       position: relative;
       width:600px;
       margin:auto;
       height:400px;
       border:1px solid red;
    }

    #son1 {
       position: absolute;
       top: 0;
       background:#f0f0f0;
    }

    #son2 {
       position: absolute;
       bottom: 0;
       background:blue;
    }
    </style>
    <body>
    <div id="father">
        <div id="son1">I am son1</div>
        <div id="son2">I am son2</div>
    </div>
    </body>
</html>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/616847.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-14
下一篇 2022-04-14

发表评论

登录后才能评论

评论列表(0条)

保存