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

H2标题换行时与下方H3文本重叠的CSS解决问询

问题描述

  • H2标题未换行时显示正常,屏幕变窄标题换行后,会与下方的H3标题(如示例中的“Se”)发生重叠。
  • 希望H3始终与上方H2文本的底部保持间距,而非基于H2原始外边距固定间距。调整margin无效,不想用media query针对特定宽度处理,寻求通用解决方案。

相关HTML代码片段

<h1>Las 8 Funciones</h1>
<div class="contenedor">
    <section class="caja funciones percepcion">
        <h2> Funciones de percepción</h2>

        <article>
            <div class="funcion sensorial extrovertida">
                
                    <h3>Se</h3>
                    <p>- Principales representantes: ESFP/ESTP  (Notable en: ISFP/ISTP)</p>
                    <p>- Descripción: Se concentra en las experiencias y sensaciones del mundo físico presente. Es muy consciente de su entorno y busca la acción y la aventura. </p>
                    <p>- Foco: 5 sentidos y tiempo presente</p>
                
            </div>
            <picture>
                <source media="(min-width:)" srcset="">
                <img src="https://live.staticflickr.com/65535/53794043780_9f18208005_m.jpg" width="239" height="240" alt="muchacho haciendo truco de skateboard">
            </picture>
        </article>

相关CSS代码片段

* {
    box-sizing: border-box;
    margin:0;
    padding:0;
}

html{
    font-size: 62.5%;
}

h1{
   font-size: 3.5rem;
}

h2{
   font-size: 2.5rem;
   height: 3rem;
   width: 100%;
}

h3{
   font-size: 2.2rem;
   width:50%;
}

p{
   font-size: 1.7rem;
}
.contenedor{
   display: flex;
   flex-wrap: wrap;
}

.caja{
   display: flex;
   flex-wrap: wrap;
   border: solid 0.2rem red;
   margin: 0.5rem;
   padding: 1rem;
}

解决方案

核心问题

你给H2设置了固定height: 3rem,当屏幕变窄文字换行时,H2的实际内容高度超过了固定高度,内容溢出后就会和下方的H3重叠;而且固定高度会让margin的计算基于这个固定值,自然无法跟随内容高度变化。

具体修复步骤

  1. 移除H2的固定高度
    删掉CSS中H2的height: 3rem,让H2的高度自动跟随内容变化:

    h2{
       font-size: 2.5rem;
       width: 100%;
       /* 移除height: 3rem */
    }
    
  2. 用margin控制间距
    给H2添加底部外边距,或者给H3添加上部外边距,确保两者之间有稳定的间距:

    /* 方案一:给H2加底部间距 */
    h2{
       margin-bottom: 1.5rem;
    }
    
    /* 或者方案二:给H3加上部间距 */
    h3{
       margin-top: 1.5rem;
    }
    
  3. 优化Flex布局(可选)
    你的.caja用了flex-wrap: wrap,H2是块级元素占满宽度,移除固定高度后,Flex会自动识别H2的实际高度,下方的article会自然排在H2下方,不会出现重叠。

这样修改后,不管H2文字是否换行,H3都会始终和H2的内容底部保持你设置的间距,不需要依赖media query,完全适配所有屏幕宽度。

内容的提问来源于stack exchange,提问作者Sebastián Martínez

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 01:33:26