Skip to content

Position 位置

控制元素在 DOM 中定位的实用工具。

ClassProperties

基本用法

静态定位元素

使用 static 来根据文档的正常流来定位元素。

任何偏移将被忽略,元素将不作为绝对定位子元素的定位参考。

Static parent

Absolute child

html
<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
<div class="relative ...">
  <p>Relative parent</p>
  <div class="absolute bottom-0 left-0 ...">
    <p>Absolute child</p>
  </div>
</div>

绝对定位元素

使用 absolute 来定位元素,使其脱离文档的正常流动,导致相邻元素表现得好像该元素不存在一样。

任何偏移量都是相对于具有位置而非 static 的最近父级计算的,元素将作为其他绝对定位的子元素的位置参考。

With static positioning

Relative parent

Static parent

Static child

Static sibling

With absolute positioning

Relative parent

Static parent

Absolute child

Static sibling

html
<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>

固定定位元素

使用 fixed 来相对于浏览器窗口定位元素。

任何偏移量都是相对于视口计算的,元素将作为绝对定位子元素的位置参考。

Contacts
Andrew Alfred
Debra Houston
Jane White
Ray Flint
Mindy Albrect
David Arnold
html
<div class="relative">
  <div class="fixed top-0 left-0 right-0">Contacts</div>
  <div>
    <div>
      <img src="..." />
      <strong>Andrew Alfred</strong>
    </div>
    <div>
      <img src="..." />
      <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
<div>
  <div>
    <div class="sticky top-0 ...">A</div>
    <div>
      <div>
        <img src="..." />
        <strong>Andrew Alfred</strong>
      </div>
      <div>
        <img src="..." />
        <strong>Aisha Houston</strong>
      </div>
      <!-- ... -->
    </div>
  </div>
  <div>
    <div class="sticky top-0">B</div>
    <div>
      <div>
        <img src="..." />
        <strong>Bob Alfred</strong>
      </div>
      <!-- ... -->
    </div>
  </div>
  <!-- ... -->
</div>

有条件地应用

悬停,焦点和其他状态

Tailwind 允许您使用变体修饰符在不同状态下有条件地应用实用程序类。例如,使用 hover:absolute 只在悬停时应用 absolute 实用程序。

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

要查看所有可用状态修饰符的完整列表,请查看悬停,焦点和其他状态文档。

断点和媒体查询

您还可以使用变体修饰符来定位媒体查询,如响应式断点、暗模式、偏好减少动作等。例如,使用 md:absolute 仅在中等屏幕尺寸及以上应用 absolute 实用程序。

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

要了解更多信息,请查看有关响应式设计深色模式其他媒体查询修改器的文档。

Released under the MIT License.