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

如何让红色线条实现响应式?(附截图)

红色线条响应式实现方案(含Bootstrap方式)

你的问题核心是代码里用了固定像素值(比如320px、1246px),这些值不会随屏幕宽度变化,导致线条位置和长度无法自适应。下面给你两种可行的解决思路:

一、纯CSS实现响应式

先重构HTML结构,把标题和线条放在同一个容器里,方便统一定位:

<div class="focus-container">
  <p class="in-focus">IN FOCUS</p>
  <div class="red-line red-hori-top"></div>
  <div class="red-line red-hori-bottom"></div>
  <div class="red-line red-vert-left"></div>
  <div class="red-line red-vert-right"></div>
</div>

然后用相对定位+绝对定位,结合calc()和百分比实现自适应:

.focus-container {
  position: relative;
  text-align: center;
  margin: 2rem 0;
}

.in-focus {
  display: inline-block;
  margin: 0;
  padding: 0 1rem; /* 避免文字和竖线重叠,可调整 */
  position: relative;
  z-index: 1; /* 让文字显示在线条上方 */
  background: #fff; /* 背景色需和页面主体背景一致,盖住中间横线 */
}

.red-line {
  position: absolute;
  background-color: red;
}

/* 上下横向线条 */
.red-hori-top, .red-hori-bottom {
  height: 1px;
  width: calc(50% - 80px); /* 50%减去文字区域宽度,可按需调整 */
}

.red-hori-top {
  top: 50%;
  left: 0;
  transform: translateY(-50%); /* 垂直居中 */
}

.red-hori-bottom {
  bottom: 50%;
  right: 0;
  transform: translateY(50%); /* 垂直居中 */
}

/* 左右纵向线条 */
.red-vert-left, .red-vert-right {
  width: 2px;
  height: 60px;
  top: 50%;
  transform: translateY(-50%); /* 垂直居中 */
}

.red-vert-left {
  left: calc(50% - 150px); /* 调整左侧位置,按需修改 */
}

.red-vert-right {
  right: calc(50% - 150px); /* 调整右侧位置,按需修改 */
}

二、Bootstrap实现响应式

利用Bootstrap内置的定位、flex类,减少自定义CSS代码,HTML结构如下:

<div class="position-relative text-center my-4">
  <p class="in-focus d-inline-block m-0 px-3 position-relative z-1 bg-white">IN FOCUS</p>
  <!-- 上横线 -->
  <div class="red-line position-absolute top-50 start-0 translate-middle-y" style="height:1px; width:calc(50% - 80px);"></div>
  <!-- 下横线 -->
  <div class="red-line position-absolute bottom-50 end-0 translate-middle-y" style="height:1px; width:calc(50% - 80px);"></div>
  <!-- 左竖线 -->
  <div class="red-line position-absolute top-50 start-50 translate-middle" style="width:2px; height:60px; margin-left:-150px;"></div>
  <!-- 右竖线 -->
  <div class="red-line position-absolute top-50 start-50 translate-middle" style="width:2px; height:60px; margin-left:150px;"></div>
</div>

只需要补充少量CSS定义线条颜色:

.red-line {
  background-color: red;
}

说明

两种方案都抛弃了固定像素的margin/padding,改用百分比和calc()动态计算位置与长度,确保屏幕尺寸变化时线条自动适配。Bootstrap方式更高效,直接复用框架内置类即可完成定位。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 23:01:04