前端学习笔记 - 元素定位

151 阅读2分钟

相对定位

元素以自身的位置作为参考点进行偏移,而不影响其他元素布局。

特点:

  • 保持文档流。
  • 不显示设置边距的情况下,对元素自身位置没有影响。
  • 不影响影响外边距margin和浮动float设置。
  • 常用于辅助定位:通常作为父容器,为绝对定位的子元素提供参考点。

示例:

.box2 {
  /* 只展示部分关键的代码 */
  position: relative;
  top: 100px;
  left: 100px;
}

绝对定位

元素以包含块作为参考点进行偏移,即位置相对于最近的拥有定位属性的祖先进行计算。如果没有找到拥有定位属性的祖先,则相对于根标签定位。

特点:

  • 脱离文档流。
  • 影响外边距margin设置。
  • 浮动float失效。
  • 一般设置父元素为相对定位,以便作为自身参考点。

示例:

  <body>
    <div class="wrap">
      <div class="box2"></div>
    <div>
  </body>
.wrap {
  /* 如果不设置定位属性,则box2会以根标签作为参考点 */
  position: relative;
}
.box2 {
  /* 只展示部分关键的代码 */
  position: absolute;
  top: 100px;
  left: 100px;
}

固定定位

元素以视口作为参考点进行偏移。

特点:

  • 参考点始终是视口。
  • 影响外边距margin设置。
  • 浮点float失效。
  • 一般用于实现浮动菜单、固定导航等。

示例:

.box2 {
  width: 200px;
  height: 200px;
  /* 将盒子固定在视窗的右下角,只展示部分关键的代码 */
  position: fixed;
  top: calc(100vh - 200px);
  left: calc(100vw - 200px);
}

粘性定位

是一种结合了相对定位和固定定位特性的布局方式。元素根据其滚动的位置在两种定位模式之间切换:

  • 当元素在其容器内没有滚动到设定的阈值时,表现为相对定位。
  • 一旦滚动到设定的阈值,表现为固定定位。

特点:

  • 参考点是距离最近的拥有滚动机制的祖先元素
  • 一般用于实现固定标题、固定导航栏等。

示例(列表标题固定头部下方):

<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>粘性定位</title>
  <style>
    .header {
      height: 100px;
      text-align: center;
      line-height: 100px;
      background-color: orange;
      font-size: 20px;
    }
    .content {
      height: 500px;
      overflow: auto;
    }
    .item {
      background-color: lightgray;
    }
    .first {
      background-color: lightblue;
      font-size: 40px;
      /* 参考点是距离最近的拥有滚动机制的祖先元素 */
      position: sticky;
      top: 0px;
    }
    h2 {
      margin: 0;
    }
  </style>
</head>
<body>
  <div class="container">
    <div class="header">头部</div>
    <div class="content">
      <div class="item">
        <div class="first">A</div>
        <h2>A1</h2>
        <h2>A2</h2>
        <h2>A3</h2>
        <h2>A4</h2>
        <h2>A5</h2>
        <h2>A6</h2>
        <h2>A7</h2>
        <h2>A8</h2>
      </div>
      <div class="item">
        <div class="first">B</div>
        <h2>B1</h2>
        <h2>B2</h2>
        <h2>B3</h2>
        <h2>B4</h2>
        <h2>B5</h2>
        <h2>B6</h2>
        <h2>B7</h2>
        <h2>B8</h2>
      </div>
      <div class="item">
        <div class="first">C</div>
        <h2>C1</h2>
        <h2>C2</h2>
        <h2>C3</h2>
        <h2>C4</h2>
        <h2>C5</h2>
        <h2>C6</h2>
        <h2>C7</h2>
        <h2>C8</h2>
      </div>
    </div>
  </div>
</body>
</html>