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

小屏幕下如何用纯CSS拆分标题块并调整元素位置

纯CSS实现响应式标题内容重排

需求概述

小屏幕设备上,将<h3>内的.heading-to-remove-on-small-screens元素移到<p>标签之后;大屏设备下保持标题为连续无换行的文本。

原始代码结构

<div class="container">
  <h3 class="heading">
    I consist of the main part
    <span class="heading-to-remove-on-small-screens pink">
      and the part that should go down on smaller screens
    </span>
  </h3>
  <p>I am the one who splits the heading on smaller screens</p>
</div>

小屏期望结构

<div class="container">
  <h3 class="heading">
    I consist of the main part
  </h3>
  <p>I am the one who splits the heading on smaller screens</p>
  <h3 class="heading-to-remove-on-small-screens pink">
    and the part that should go down on smaller screens
  </h3>
</div>

解决方案

不用重复内容,用CSS Grid就能搞定,具体操作:

  • 大屏布局设置:给容器加Grid布局,通过display: contents让<h3>的子元素直接参与网格排列,避免标题换行
.container {
  display: grid;
  /* 大屏下两行:第一行放完整标题,第二行放段落 */
  grid-template-areas: "full-heading" "paragraph";
}

.heading {
  display: contents; /* 让h3本身不生成盒子,子元素直接成为网格项 */
}

/* 标题主内容和span都放在full-heading区域,自动同行排列 */
.heading::before {
  content: "";
  grid-area: full-heading;
}
.heading > span {
  grid-area: full-heading;
}

p {
  grid-area: paragraph;
}

这里的display: contents是核心,它能让<h3>里的文本和<span>直接在Grid容器里并排,自然保持连续,不会出现不必要的换行。

  • 小屏响应式调整:用媒体查询重新定义网格区域,把<span>移到段落之后
@media (max-width: 768px) {
  .container {
    /* 小屏下单列:标题主内容 → 段落 → 要移动的span */
    grid-template-areas: "main-heading" "paragraph" "moved-part";
  }

  .heading::before {
    grid-area: main-heading;
  }

  .heading > span {
    grid-area: moved-part;
    display: block; /* 让span单独占一行,和原标题视觉上分开 */
  }
}
  • 保留原有样式,比如粉色文字:
.pink {
  color: pink;
}

这样就能完美实现需求:大屏下标题是连续无换行的文本,小屏时指定部分自动移到段落后面,全程纯CSS,没有重复内容这类不良实践。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 21:28:21