【每日面试题】position 有哪些值,分别作用是什么

356 阅读1分钟

static - 默认属性

HTML 元素默认情况下的定位为 static(静态);

静态定位的元素不受 top、bottom、left、right 属性的影响;

position: static; 的元素不会以任何特殊方式定位;它始终根据页面的正常流进行定位。

relative

position: relative; 的元素相对于其正常位置进行定位。

设置相对定位的元素的 top、bottom、left、right 属性将导致其偏离其正常位置进行调整。不会对其余内容进行调整来适应元素留下任何空间。

absolute

position: absolute; 的元素相对于最近的定位祖先元素进行定位(而不是相对于视口定位),

然而,如果绝对定位的元素没有祖先,它将使用文档主体(body),并随页面滚动一起滚动。

注意:“被定位的”元素是其位置除 static 以外的任何元素。

fixed

position: fixed; 的元素是相对于视口定位的,这意味着即使滚动页面,它也始终位于同一位置。top、right、bottom、left 属性用于定位此元素。

固定定位的元素不会在页面中通常应放置的位置上留出空隙。

sticky

position: sticky; 的元素根据用户的滚动位置进行定位。

粘性元素根据滚动位置在相对(relative)和固定(fixed)之间切换。起先它会被相对定位,直到在视口中遇到给定的偏移位置为止 - 然后将其“粘贴”在适当的为止(比如 position: fixed;)

<style> 
    body {
        height: 2000px;
    }
    .box {
        width: 100px;
        height: 50px;
        background-color: #ddd;
        margin-bottom: 30px;
    }
    .box2 {
        width: 50px;
        height: 30px;
        background-color: red;
    }
</style>

<div class="box" style="position: static; left: 30px;">static</div>
<div class="box" style="position: relative; left: 30px;">relative</div>
<div class="box" style="position: relative;">
  <div class="box2" style="position: absolute; left: 20px;">absolute</div>
</div>
<div class="box" style="position: fixed; top: 30px; left: 150px;">fixed</div>
<div class="box" style="position: sticky; top: 20px;">sticky</div>

WX20210331-154347.png

WX20210331-154430.png