PAYATHON 2026

CSS 如何让线条跟随标题文本并保持装饰元素相邻?

数据阿明

结论

将标题和装饰组放进同一个可换行的 flex 容器,让 .line-and-square 作为整体换行。装饰组内部仍使用 flex 布局:线条伸展填充剩余空间,方块保持固定宽度。

.component {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  align-items: center;
  gap: 10px;
}

.title {
  flex: 0 1 auto;
  min-width: 0;
  margin: 0;
}

.line-and-square {
  display: flex;
  flex: 1 0 40px;
  align-items: center;
  gap: 10px;
}

.line {
  flex: 1;
  height: 3px;
  background-color: red;
}

.square {
  flex: 0 0 20px;
  width: 20px;
  height: 20px;
  background-color: red;
}
<div class="component">
  <h1 class="title">How can you ensure that the line follows the text in all circumstances?</h1>
  <div class="line-and-square">
    <div class="line"></div>
    <div class="square"></div>
  </div>
</div>

为什么这样设置

.component 的 flex-wrap: wrap 会在宽度不足时让标题和装饰组换到下一行。由于 .line-and-square 是一个 flex 子项,内部的线条和方块会保持在一起,随装饰组整体移动。

.line-and-square 的 flex: 1 0 40px 让装饰组在有剩余空间时伸展,同时保留容纳线条、间距和方块的基础宽度。.line 使用 flex: 1 填满组内剩余空间;.square 使用 flex: 0 0 20px 保持固定宽度。

注意事项

标题目前仍是英文示例文本。换成实际标题后,其宽度和换行位置会随容器宽度变化。如果容器窄到无法同时容纳标题和装饰组的最小宽度,装饰组会整体换行。原问题没有提供实际渲染截图,因此无法判断当前页面具体的视觉差异。

备注:内容仅供参考。