position是css为某些元素提供定位的属性,它有五种常规取值,本篇文章将会详细介绍。

1.静态定位

静态定位:position取值为static,他是HTML文档元素的默认值,不受top、bottom、left、right属性影响,并且不能进行z-index分层,元素在正常的文档流中。
代码演示:

<style>
      div{
          background-color: gray;
          width: 400px;
          height: 300px;
          top: 400px;
          left: 400px;
      }
</style>
<body>
    <div>

    </div>
    
</body>

网页展示效果:
静态定位展示效果

2.相对定位

相对定位:当position取值为relative时,该元素为相对定位,相对自身位置定位,不会脱离文档流,可以使用z-index进行分层。它可以根据文档正常流动偏移相对于它本身top、bottom、right和left的值,偏移量不会影响其他元素的位置。
静态定位是默认值,以下示例用图1为静态定位、图2为相对定位,对比理解
代码展示:

<style>
      .a1{
          background-color: gray;
          width: 400px;
          height: 300px;
          top: 400px;
          left: 400px;
      }
      .a2{
        background-color: rgb(188, 231, 86);
          width: 400px;
          height: 300px;
          top: 100px;
          left: 100px;
          position: relative;
      }
</style>
<body>
    <div class="a1">

    </div>
    <div class="a2">

    </div>
</body>

网页效果展示:
网页效果展示

3.绝对定位

绝对定位:当position取值为absolute元素是绝对定位,脱离文档流的布局,后面的元素会填补它空下来的位置,它的起始位置为最近的position值不是static的父元素,若没有则是以HTML为准,由top、bottom、left、right确定最终位置,可以使用z-index 进行分层。
以下示例图一为静态定位,图二为绝对定位
代码展示:

<style>
      .a1{
          background-color: gray;
          width: 400px;
          height: 300px;
          top: 400px;
          left: 400px;
      }
      .a2{
        background-color: rgb(188, 231, 86);
          width: 600px;
          height: 200px;
          top: 100px;
          left: 100px;
          position:absolute;
      }
</style>
<body>
    <div class="a1">

    </div>
    <div class="a2">

    </div>
</body>

网页效果展示:
静态定位和绝对定位的对比
以下示例图一为相对定位,图二为绝对定位
代码展示:

<style>
      .a1{
          background-color: gray;
          width: 400px;
          height: 300px;
          top: 50px;
          left: 50px;
          position: relative;
      }
      .a2{
        background-color: rgb(188, 231, 86);
          width: 600px;
          height: 200px;
          top: 100px;
          left: 100px;
          position:absolute;
      }
</style>
<body>
    <div class="a1">

    </div>
    <div class="a2">

    </div>
</body>

网页展示效果:
相对定位和绝对定位对比
以下示例为父元素是相对定位,子元素为绝对定位
代码演示:

<style>
      .a1{
          background-color: gray;
          width: 400px;
          height: 300px;
          top: 50px;
          left: 50px;
          position: relative;
      }
      .a2{
        background-color: rgb(188, 231, 86);
          width: 600px;
          height: 200px;
          top: 100px;
          left: 100px;
          position:absolute;
      }
</style>
<body>
    <div class="a1">
        <div class="a2">

        </div>
    </div>
    
网页展示效果:

父元素为相对定位子元素为绝对定位对比

4.固定定位

笃定定位:当position的取值为fixed时,该元素为固定定位,脱离文档流,它的起始起始位置相对于视口且是固定位置不随滚动条的滑动而滚动。一般像导航栏大多数会使用固定定位。

5.粘性定位

粘性定位:当position取值为sticky时该元素为粘性定位,它也会脱离文档流,会在文档流中预留该元素的物理空间;它的相对偏移是相对于父标签而言,设置top等值只会在父标签中sticky。

Logo

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

更多推荐