前端学习笔记52-相对定位

问题

看代码

<!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{
            width: 100px;
            height: 100px;
            background-color: #bfa;
        }
        .box2{
            width: 100px;
            height: 100px;
            background-color: orange;
        }
        .box3{
            width: 100px;
            height: 100px;
            background-color: orchid;
        }
    </style>
</head>
<body>
    <div class="box1">1</div>
    <div class="box2">2</div>
    <div class="box3">3</div>
</body>
</html>

在这里插入图片描述
如果想把box2移动到box1右边,而box3不动,怎么做呢?
可以设置box2和box3的margin。

        .box2{
            width: 100px;
            height: 100px;
            background-color: orange;
            margin-top: -100px;
            margin-left: 100px;
        }
        .box3{
            width: 100px;
            height: 100px;
            background-color: orchid;
            margin-top: 100px;
        }

在这里插入图片描述
但是这样就很麻烦,得设置两个box,如果用浮动来实现,也很复杂。
因此,得用定位来随意摆放box2而不动其他的元素。
定位是一种更加高级的布局手段,可以将元素摆放在页面的任意位置。

position

可选值:
 static:默认值,元素是静止的,没有开启定位
 relative:开启元素的相对定位
 absolute:开启元素的绝对定位
 fixed:开启元素的固定定位
 sticky:开启元素的粘滞定位

相对定位

position:relative
如果不设置偏移量,元素不发生任何变化。
那何为偏移量(offset)?
偏移量可以设置元素的位置。
有:
  top:元素与定位位置上面的距离

        .box2{
            width: 100px;
            height: 100px;
            background-color: orange;
            position: relative;
            top: 50px;
        }

在这里插入图片描述

  bottom:元素与定位元素下边的距离。

        .box2{
            width: 100px;
            height: 100px;
            background-color: orange;
            position: relative;
            bottom: 50px;
        }

在这里插入图片描述
肯定有人疑惑,两个都设置,会咋样

        .box2{
            width: 100px;
            height: 100px;
            background-color: orange;
            position: relative;
            top: 50px;
            bottom: 50px;

        }

在这里插入图片描述
显然,top有效,bottom无效。因为可以设置负值,所以通常用一个就行了。
  left:元素和定位位置左侧的距离。
  right元素和定位位置右侧的距离。
这里就不解释了,和top、bottom类似。

解决问题

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

在这里插入图片描述

定位位置

前面说的定位位置是什么?
定位位置是元素在文档流中的位置,也就是开启定位前的那个位置。

相对定位会提升元素的层级

从前面的效果可以看到,如果重叠了,是box2覆盖其他的box,所以box2的层级较高。

相对定位不会使回溯脱离文档流

虽然层级提升,但是它没有脱离文档流,否则box3就上去了。

相对定位不会改变元素的性质

块还是块,行内还是行内

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小欣CZX

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值