You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让网页中的链接固定位置,不随页面内容变化而移动?

解决链接位置固定的几种方案

当前链接属于文档流内容,页面文本增多时会被向下挤压,导致位置不一致。可以通过以下几种方法让链接固定在同一位置:

方法一:固定定位(Fixed Positioning)

将链接容器设置为固定定位,使其相对于浏览器视口固定位置,即使页面滚动也不会移动。

修改后的CSS代码:

/* 固定链接容器位置 */
.header {
  position: fixed;
  top: 20px; /* 距离顶部的距离,可自行调整 */
  left: 20px; /* 距离左侧的距离,可自行调整 */
}

.header a {
  color: rgb(235, 238, 205);
  text-align: left;
  padding: 10px;
  font-size: 18px;
  line-height: 25px;
  border-radius: 4px;
  display: block; /* 让链接垂直排列,替代<br>标签更规范 */
}

h1 {
  text-align: center;
}

p {
  text-align: center;
  margin: 0 auto;
  max-width: 80%; /* 避免正文和链接重叠 */
}

对应的HTML可去掉<br>标签:

<body>
  <h1> Default Title </h1>
  <p>Temporary paragraph text.</p>
  <div class="header">
    <a href="Page 1">Test Page 1</a>
    <a href="Page 2">Test Page 2</a>
    <a href="Page 3">Test Page 3</a>
    <a href="Page 4">Test Page 4</a>
    <a href="Page 5">Test Page 5</a>
  </div>
</body>

方法二:绝对定位(Absolute Positioning)

给父容器(比如<body>)设置相对定位,再将链接容器设置为绝对定位,使其相对于父容器固定位置。

修改后的CSS代码:

/* 给body设置相对定位作为参考 */
body {
  position: relative;
  min-height: 100vh; /* 确保body占满视口高度 */
}

.header {
  position: absolute;
  top: 20px;
  left: 20px;
}

.header a {
  color: rgb(235, 238, 205);
  text-align: left;
  padding: 10px;
  font-size: 18px;
  line-height: 25px;
  border-radius: 4px;
  display: block;
}

h1 {
  text-align: center;
}

p {
  text-align: center;
  margin: 0 auto;
  max-width: 80%;
}

这种方法下,链接会跟着页面滚动而移动,适合不需要链接始终悬浮的场景。

方法三:Grid布局

用Grid将页面划分为固定的链接区域和内容区域,两者互不干扰,内容多少不会影响链接位置。

修改后的CSS代码:

body {
  display: grid;
  grid-template-columns: 200px 1fr; /* 左侧200px放链接,右侧占剩余空间 */
  gap: 20px;
  min-height: 100vh;
  padding: 20px;
  box-sizing: border-box;
}

.header {
  grid-column: 1 / 2; /* 链接放在第一列 */
}

.header a {
  color: rgb(235, 238, 205);
  text-align: left;
  padding: 10px;
  font-size: 18px;
  line-height: 25px;
  border-radius: 4px;
  display: block;
}

.content {
  grid-column: 2 / 3; /* 内容放在第二列 */
}

h1 {
  text-align: center;
}

p {
  text-align: center;
}

对应的HTML需要把标题和段落放在内容容器里:

<body>
  <div class="header">
    <a href="Page 1">Test Page 1</a>
    <a href="Page 2">Test Page 2</a>
    <a href="Page 3">Test Page 3</a>
    <a href="Page 4">Test Page 4</a>
    <a href="Page 5">Test Page 5</a>
  </div>
  <div class="content">
    <h1> Default Title </h1>
    <p>Temporary paragraph text.</p>
  </div>
</body>

这种布局更结构化,适合需要区分侧边栏和内容区的场景。

内容的提问来源于stack exchange,提问作者dangoqut132

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 14:33:10