针对定位的区别及使用我整理一些方法

css的学习中,开篇就是相对定位和绝对定位的使用,大家在学习的过程中不免被其绕晕,所以我按照自己的理解对其进行了整理及分析,仅供参考学习。


未进行定位,用以下面俩种定位的区别
在这里插入图片描述

一、绝对定位

可以将绝对定位理解为以浏览器为父节点来定位自己
代码如下(示例):

    <style>
        body {
            background-color: aquamarine;
        }
        div {
            width: 100px;
            height: 100px;
            background-color: pink;
            position: absolute;
            left: 0;
            top: 0;
        }
    </style>
</head>
<body>
<div></div>
</body>

在这里插入图片描述

二、相对定位

相对定位可以理解为“相对于”它的起点进行移动。
代码如下(示例):

    <style>
        body {
            background-color: aquamarine;
        }
        div {
            width: 100px;
            height: 100px;
            background-color: pink;
            position: relative;
            left: 0;
            top: 0;
        }
    </style>
</head>
<body>
<div></div>

在这里插入图片描述

三、绝对定位与相对定位的区别

绝对定位使元素的位置与文档流无关,因此不占据空间。可以理解为绝对定位将元素从原来位置拿走,后面的元素就会占据绝对定位元素的位置。如同排队一样,前面的人走了,后面的人就会前进占去离开的人的位置。

    <style>
        body {
            background-color: aquamarine;
        }
        .box {
            width: 100px;
            height: 100px;
            background-color: pink;
            float: left;
            margin: 15px;
        }
        .twe {
            position:absolute;
            left: 20px;
            top: 20px;
        }
    </style>
</head>
<body>
<div class="box one">1</div>
<div class="box twe">2</div>
<div class="box three">3</div>
<div class="box four">4</div>
</body>

在这里插入图片描述


相对定位与绝对定位相反,它移动后原本所占的空间仍保留。可理解为它进行定位后,之前的位置后面的元素不可占据。如同私人车库停车一样,车子离开后,别的车不可以停在那个车库。
    <style>
        body {
            background-color: aquamarine;
        }
        .box {
            width: 100px;
            height: 100px;
            background-color: pink;
            float: left;
            margin: 15px;
        }
        .twe {
            position:relative;
            left: 20px;
            top: 20px;
        }
    </style>
</head>
<body>
<div class="box one">1</div>
<div class="box twe">2</div>
<div class="box three">3</div>
<div class="box four">4</div>
</body>

在这里插入图片描述

四、绝对定位与相对定位的使用

在日常的使用定位时,普遍以父节点为相对定位,子节点为绝对定位
此方法可简称为“子绝父相”。

    <style>
        .a{
            width: 400px;
            height: 400px;
            position: relative;
            left: 100px;
            top: 100px;
            background-color: aquamarine;
        }
        .b {
            width: 100px;
            height: 100px;
            position: absolute;
            left: 100px;
            top: 100px;
            background-color: pink;
        }
    </style>
</head>
<body>
<div class="a">
    <div class="b"></div>
</div>
</body>

在这里插入图片描述


结语

以上就是我对绝对定位和相对定位的理解和整理,如果还对定位不太理解,可留言或私信我,我会尽可能的提供帮助。

如果文章对你有帮助的话,请给我一个小小的点赞一波哦!每个赞和评论都是我编写文章的动力哦!

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐