Skip to content
全部文档

position

用于控制元素在文档中如何定位的工具类。

快速参考

属性
staticposition: static;
fixedposition: fixed;
absoluteposition: absolute;
relativeposition: relative;
stickyposition: sticky;

示例

静态定位元素

使用 static 工具类按照文档的正常流定位元素:

Static parent

Absolute child

html
<!-- [!code classes:static] -->
<div class="static ...">
  <p>Static parent</p>
  <div class="absolute bottom-0 left-0 ...">
    <p>Absolute child</p>
  </div>
</div>

对于静态定位的元素,任何偏移都会被忽略,且该元素不会作为绝对定位子元素的定位参照。

相对定位元素

使用 relative 工具类按照文档的正常流定位元素:

Relative parent

Absolute child

html
<!-- [!code classes:relative] -->
<div class="relative ...">
  <p>Relative parent</p>
  <div class="absolute bottom-0 left-0 ...">
    <p>Absolute child</p>
  </div>
</div>

对于相对定位的元素,任何偏移都相对于元素的正常位置计算,且该元素会作为绝对定位子元素的定位参照。

绝对定位元素

使用 absolute 工具类将元素定位到文档正常流之外,使相邻元素表现得像该元素不存在一样:

With static positioning

Relative parent

Static parent

Static child?

Static sibling

With absolute positioning

Relative parent

Static parent

Absolute child

Static sibling

html
<!-- [!code classes:absolute] -->
<div class="static ...">
  <!-- Static parent -->
  <div class="static ..."><p>Static child</p></div>
  <div class="inline-block ..."><p>Static sibling</p></div>
  <!-- Static parent -->
  <div class="absolute ..."><p>Absolute child</p></div>
  <div class="inline-block ..."><p>Static sibling</p></div>
</div>

对于绝对定位的元素,任何偏移都相对于最近的、定位不为 static 的父元素计算,且该元素会作为其他绝对定位子元素的定位参照。

固定定位元素

使用 fixed 工具类相对于浏览器窗口定位元素:

Contacts
Andrew Alfred
Debra Houston
Jane White
Ray Flint
Mindy Albrect
David Arnold
html
<!-- [!code classes:fixed] -->
<div class="relative">
  <div class="fixed top-0 right-0 left-0">Contacts</div>
  <div>
    <div>
      <img src="/img/andrew.jpg" />
      <strong>Andrew Alfred</strong>
    </div>
    <div>
      <img src="/img/debra.jpg" />
      <strong>Debra Houston</strong>
    </div>
    <!-- ... -->
  </div>
</div>

对于固定定位的元素,任何偏移都相对于视口计算,且该元素会作为绝对定位子元素的定位参照:

粘性定位元素

使用 sticky 工具类将元素按 relative 定位,直到它越过指定阈值,之后将其视为 fixed,直到其父元素滚出屏幕:

A
Andrew Alfred
Aisha Houston
Anna White
Andy Flint
B
Bob Alfred
Bianca Houston
Brianna White
Bert Flint
C
Colton Alfred
Cynthia Houston
Cheyenne White
Charlie Flint
html
<!-- [!code classes:sticky,top-0] -->
<div>
  <div>
    <div class="sticky top-0 ...">A</div>
    <div>
      <div>
        <img src="/img/andrew.jpg" />
        <strong>Andrew Alfred</strong>
      </div>
      <div>
        <img src="/img/aisha.jpg" />
        <strong>Aisha Houston</strong>
      </div>
      <!-- ... -->
    </div>
  </div>
  <div>
    <div class="sticky top-0">B</div>
    <div>
      <div>
        <img src="/img/bob.jpg" />
        <strong>Bob Alfred</strong>
      </div>
      <!-- ... -->
    </div>
  </div>
  <!-- ... -->
</div>

对于粘性定位的元素,任何偏移都相对于元素的正常位置计算,且该元素会作为绝对定位子元素的定位参照。

响应式设计

使用 md: 等断点变体作为 position 工具类的前缀,即可仅在中等及以上屏幕尺寸下应用该工具类:

html
<div class="relative md:absolute ...">
 <!-- ... -->
</div>

了解如何使用变体,请参阅变体文档

文档译文以 MIT 协议授权;原文版权归 Tailwind Labs。湘ICP备2026005453号-2