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

CSS边框内部留白过多,如何让文字适配边框?

解决CSS边框内部留白过多的问题

问题原因

  • header元素设置了padding: 10% 10%,大幅撑开了容器内部空间
  • .welcome作为块级元素默认占满父容器宽度,导致边框跟着撑宽,和内部文字尺寸不匹配

修复方案

调整以下几点:

  1. 给.welcome添加width: fit-content,让容器宽度自动适配内部文字
  2. 设置.welcome为margin: 50px auto 0,使其在header中水平居中
  3. 调整header的内边距为更合理的值,避免过度留白;注意.welcome中padding-bottom: 10%会被后续padding: 10px覆盖,需统一内边距设置

修改后的代码

CSS代码

* { 
  box-sizing: border-box; 
  margin: 0; 
}
@media screen and (max-width: 600px) { 
  header, .welcome { 
    width: 100%; 
  } 
  .nav>ul { 
    display: flex; 
    justify-content: flex-end; 
    right: 0; 
    padding: 0; 
    margin: auto; 
  }
}
header { 
  background-color: rgb(237, 239, 240); 
  padding: 2rem 1rem; /* 调整为更合理的内边距 */
  font-family: Helvetica; 
  display: flex; 
  justify-content: center;
}
.welcome { 
  display: block; 
  text-align: center; 
  margin: 50px auto 0; 
  border: white solid 4px; 
  padding: 10px; 
  width: fit-content; /* 关键:自适应文字宽度 */
}
h2 { 
  margin: 0; 
  margin-bottom: 0.2rem; 
}
p { 
  margin-block-start: 1em; 
}

HTML代码

<header> 
  <section class="welcome" id="welcome-section"> 
    <h2>Rishav Verma</h2> 
    <p>Web Developer</p> 
  </section>
</header>

修改后边框会紧密贴合文字内容,不再出现多余留白。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 09:25:10