Menu
CoddyTech

固定定位

本课属于 Coddy HTML 学习旅程的“使用 CSS 添加样式”单元。第 58 课,共 76 课。

在 CSS 中,固定定位会让元素始终停留在屏幕上的同一位置,无论你滚动多少。当你设置 position: fixed; 时,元素会从正常布局中移除,因此其他元素会忽略它。它会固定在浏览器窗口中,适合用于需要始终可见的页眉、页脚或菜单。

以下是使用固定定位的基本语法:

selector {
    position: fixed;
    top: value;
    right: value;
    bottom: value;
    left: value;
}
  • position: fixed;:此声明会将元素的定位方式设置为固定定位。
  • top、right、bottom、left:这些属性用于指定元素相对于视口的位置。你可以使用正值或负值,单位可以是像素(px)、em(em)、百分比(%)或其他有效的 CSS 单位。

例如:

.header {
    position: fixed;
    top: 0;
    left: 0;
}

在这个示例中,带有 header 类的元素通过 position: fixed;、top: 0; 和 left: 0; 固定在视口顶部。 

challenge icon

挑战

简单

给你一个包含页眉(<div>)和段落(<p>)的 HTML 文档。你的任务是使用固定定位,让页眉在滚动页面时仍停留在视口顶部。按照以下步骤操作:

  1. 编写一条 CSS 规则,选择具有 header 类的 <div> 元素。
  2. 将 .header 元素的 position 属性设为 fixed。
  3. 将 .header 元素的 top 属性和 left 属性都设为 0。这样会将页眉定位在视口的左上角。
  4. 将 .header 元素的 width 属性设为 100%,使其横跨整个视口。
  5. 将 .header 元素的 background-color 属性设为 #fcc726(金黄色),使它在页面内容的衬托下清晰可见。
  6. 将 text-align 属性设为 center,这样看起来会更好。

亲手试试

<html>
<head>
    <title>Fixed Positioning</title>
    <style>
        /* Write CSS rules here */
    </style>
</head>
<body>
    <div class="header">This is the header</div>
    <p>This is some content below the header. Scroll down to see the fixed positioning in action.</p>
    <p>More content here...</p>
    <p>More content here...</p>
    <p>More content here...</p>
    <p>More content here...</p>
    <p>More content here...</p>
    <p>More content here...</p>
    <p>More content here...</p>
    <p>More content here...</p>
    <p>More content here...</p>
    <p>More content here...</p>
    <p>More content here...</p>
    <p>More content here...</p>
    <p>More content here...</p>
    <p>More content here...</p>
    <p>More content here...</p>
    <p>More content here...</p>
    <p>More content here...</p>
    <p>More content here...</p>
</body>
</html>
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

使用 CSS 添加样式中的所有课

自己练习: Web 在线编辑器