css之position定位

自学前端系列之HTML与CSS

第十一节:CSS之position定位

1.static(静态定位)

是 position 属性的默认值,表示块保留在原本位置,不会被top bottom left right和z-index重新定位。

<!DOCTYPE html>
<html>
  <head>
    <style>
      div {
        height: 50px;
        width: 20px;
        position: static;
        top: 100px;
        left: 100px;
        background-color: aquamarine;
      }
    </style>
  </head>
  <body>
    <div></div>
  </body>
</html>

由于位置是static,所以它并不在top:100px;left:100px的地方,而在top:0px;left:0px的地方
在这里插入图片描述

2.fixed(固定定位)

相对于浏览器的创建进行定位,可使用 top、right、bottom、left 这 4 个属性来定义元素相对于浏览器窗口的位置。由于元素被固定不会随着滚动条的拖动而改变位置,所以出现在每页的固定位置。

<!DOCTYPE html>
<html>
  <head>
    <style>
      .body {
        overflow: scroll;
        width: 10px;
      }
      div {
        height: 70px;
        width: 50px;
        position: fixed;
        top: 100px;
        left: 100px;
        background-color: rgb(32, 142, 233);
      }
    </style>
  </head>
  <body class="body">
    <div></div>
  </body>
</html>

在这里插入图片描述

3.relative(相对定位)

相对定位将元素从原来的位置通过 top、bottom、left 和 right 四个属性向上、向下、向左或者向右移动来定位。它的元素可以移动并与其他元素重叠,但会保留元素默认位置处的空间。

<!DOCTYPE html>
<html>
 <head>
   <style>
     div {
       border: 1px solid black;
     }
     div.decorate {
       width: 150px;
       height: 100px;
       background-color: #2da107;
       position: relative;
       top: 50px;
       left: 30px;
     }
     p {
       width: 100px;
       height: 100px;
       background-color: rgb(109, 56, 56);
     }
   </style>
 </head>
 <body>
   <div>
     <div class="decorate"></div>
     <p></p>
   </div>
 </body>
</html>

在这里插入图片描述

4.absolute(绝对定位)

绝对定位,是相对于最近的且不是static定位的父元素来定位。如果找不到符合条件的父级元素则会相对与浏览器窗口来进行定位。可以使用 top、bottom、left 和 right 四个属性来设置元素相对于父元素或浏览器窗口不同方向上的移动量

<!DOCTYPE html>
<html>
  <head>
    <style>
      div {
        border: 1px solid black;
      }
      div.decorate {
        width: 150px;
        height: 100px;
        background-color: #2da107;
        position: absolute;
        top: 50px;
        left: 30px;
      }
      p {
        width: 100px;
        height: 100px;
        background-color: rgb(109, 56, 56);
      }
    </style>
  </head>
  <body>
    <div>
      <div class="decorate"></div>
      <p></p>
    </div>
  </body>
</html>

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值