CSS 绝对定位和相对定位

3 篇文章 0 订阅

绝对定位和相对定位 代码练习(仅供参考)

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .box1 {
            position: relative;
            top: 60px;
            width: 400px;
            height: 400px;
            border: 1px solid #000;
            background-color: #fff;
        }

        .box2 {
            position: relative;
            left: 40px;
            width: 300px;
            height: 300px;
            background-color: orange;
        }

        .box3 {
            position: absolute;
            right: 20px;
            top: 40px;
            width: 100px;
            height: 100px;
            background-color: #6cf;
        }

        .box4 {
            width: 50px;
            height: 50px;
            position: absolute;
            background-color: #0e0;
            right: 40px;
            top: 10px;
        }

        .box5 {
            position: absolute;
            width: 400px;
            height: 400px;
            right: 100px;
            background-color: #000;
            /* z-index: 999; */
        }
    </style>
</head>

<body>
    <!-- 1.相对定位:relative  自己占据位置 不会给其他元素占用 相对于自己占有的原有位置移动 -->
    <!-- 2.绝对定位:absolute  脱离标准流, 往上级去找最接近定位元素进行相对移动, 上级可以是绝对定位,也可以是相对定位, -->
    <!-- 3.box4 的上级定位元素就是box3(使用了absolute)  box4的移动相对于box3的定位  -->
    <!-- 4.嵌套包含的关系 box2移动 ,box3和box4作为子级盒子会跟着移动 -->
    <!-- CSS中定位方式有static,absolute,fixed,relative,
        而使得元素脱离文档标准流的定位方式只有absolute和fixed两种方式。
        其它两种方式任然会占有原来的地方。
     -->
    <!--5. box5 与box1是同层级的关系 box5的定位往上级找定位元素就是body当前页面窗口了,相对于当前的浏览器窗口移动 -->
    <!--6  box5 在元素布局排列在box1之前 box5脱离了标准流 会漂浮起来,原有的位置会被box1占用,box1在顶层(用了relative)
            如果这时候box5想显示在页面最顶层,可以用z-index:999 就可以反过来把黑色的box1压住了
      -->
      <div class="box5"></div>
    <div class="box1">
        <div class="box2">
            <div class="box3">
                <div class="box4">123</div>
            </div>
        </div>
    </div>
    <!-- 总结就是 绝对定位会脱离标准流 往上级找定位元素进行定位移动  相对定位会自己占据原有位置,相对于自己原有的位置移动
        同层级均有定位的情况下 用z-index 可以定义页面显示的层级关系
     -->
</body>

</html>

在这里插入图片描述
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值