固定定位
本课属于 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; 固定在视口顶部。
挑战
简单给你一个包含页眉(<div>)和段落(<p>)的 HTML 文档。你的任务是使用固定定位,让页眉在滚动页面时仍停留在视口顶部。按照以下步骤操作:
- 编写一条 CSS 规则,选择具有
header类的<div>元素。 - 将
.header元素的position属性设为fixed。 - 将
.header元素的top属性和left属性都设为0。这样会将页眉定位在视口的左上角。 - 将
.header元素的width属性设为100%,使其横跨整个视口。 - 将
.header元素的background-color属性设为#fcc726(金黄色),使它在页面内容的衬托下清晰可见。 - 将
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>这节课包含一个小测验。开始学习即可作答,并记录你的进度。
使用 CSS 添加样式中的所有课
自己练习: Web 在线编辑器