相对定位与绝对定位

1、相对定位

格式:position: relative;

相对定位不脱离标准流,仍然在标准流中占有位置,相对定位的移动是相对于在标准流中的位置。

相对定位区分块级元素、行内元素与行内块级元素,即使该元素为相对定位,也不改变元素性质。

当使用相对定位时,一般不使用margin、padding等元素,会影响标准流布局。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>标题</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        .box1 {
            height: 200px;
            width: 200px;
            background-color: red;
            left: 120px;
            position: relative;
        }

        .box2 {
            height: 200px;
            width: 200px;
            background-color: blue;
        }

        .box3 {
            height: 200px;
            width: 200px;
            background-color: yellow;
        }

        span {
            height: 200px;
            width: 200px;
            background-color: #ccc;
        }
    </style>
</head>
<body>
<div class="box1"><p>我是块级元素1</p></div>
<div class="box2"><p>我是块级元素2</p></div>
<div class="box3"><p>我是块级元素3</p></div>
<span>我是行内元素</span>
</body>
</html>

 

 2、绝对定位

格式:position: absolution;

绝对定位脱离于标准流,与浮动流类似,绝对定位的移动是根据body标签来做参考的。

绝对定位不区分块级元素、行内元素、行内块级元素。

当祖先标签(父标签、父标签的父标签……)为绝对定位,则该标签默认根据距离自己最近的绝对定位做参考。

绝对定位在以body为参考时,参考的是页面当前大小,而不是以页面整体大小为参考。

绝对定位会忽略祖先元素的内边距。

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>标题</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        .box1 {
            height: 200px;
            width: 200px;
            background-color: red;
        }

        .box2 {
            height: 200px;
            width: 200px;
            background-color: blue;
            position: absolute;
            top: 30px;
            left: 50px;
        }

        .box3 {
            height: 300px;
            width: 300px;
            background-color: aqua;
            position: absolute;
        }

        .box4 {
            height: 100px;
            width: 100px;
            background-color: darkorange;
            position: absolute;
            top: 0;
            left: 0;
        }
    </style>
</head>
<body>
<div class="box1">
    <div class="box2"></div>
</div>

<div class="box3">
    <div class="box4"></div>
</div>
</body>
</html>

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值