首页 > 编程开发 > CSS    日期:2020-11-01 / 浏览

大家知道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>

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

觉得上面的内容有用吗?快来点个赞吧!

点赞() 我要打赏

温馨提示 : 本站内容来自会员投稿以及互联网,所有源码及教程均为作者总结编辑,请大家在使用过程中提前做好备份,以免发生无法预知的错误,源码类教程请勿直接用于生产环境!

 可能感兴趣的文章

1 2 3 4 5