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

如何用CSS实现标题在div游戏推荐盒子上方居中显示?

你现在的布局问题主要有两个核心原因:

  1. .game-section 设置了display: inline-flex且没有指定flex方向,默认是水平排列,所以标题和三个游戏盒子被排在了同一行
  2. 标题的ID选择器写错了,HTML里h1的id是games,CSS里写的是#game,对应的样式完全不生效

修改方案

方案1(推荐,结构更规范,适配性更好)

第一步:调整HTML结构

把三个游戏盒子放到一个单独的容器里,同时删掉没用的<br>标签:

<div class="second-box">
  <div class="game-section">
    <h1 id="games"> Game Recommendations </h1>
    <!-- 新增游戏卡片容器 -->
    <div class="game-card-wrap">
      <div class="box1">
        <p> This is the first game </p>
      </div>
      <div class="box2">
        <p> This is the second game </p>
      </div>
      <div class="box3">
        <p> This is the third game </p>
      </div>
    </div>
  </div>
</div>
第二步:替换原有CSS
.game-section{
  min-height: 400px; /* 改min-height避免内容溢出 */
  width: 100%;
  background-color: darkkhaki;
  display: flex;
  flex-direction: column; /* 子元素垂直排列,标题在上、卡片容器在下 */
  align-items: center; /* 子元素水平居中 */
  padding: 20px 0; /* 加上下内边距避免内容贴边 */
}

/* 修正ID选择器 */
#games{
  font-size: 23px;
  text-align: center;
  margin: 0 0 20px 0; /* 加下边距和下面的卡片拉开距离 */
}

/* 新增卡片容器样式,控制卡片水平排列 */
.game-card-wrap {
  display: flex;
  gap: 20px; /* 统一控制卡片间距 */
  flex-wrap: wrap; /* 屏幕宽度不够时自动换行,适配移动端 */
  justify-content: center;
}

.box1{
  background-color: darkolivegreen;
  height:230px;
  width: 250px;
}

.box2{
  background-color: rgba(108, 148, 39, 0.267);
  height:230px;
  width: 250px;
}

.box3{
  background-color:rgb(104, 99, 26);
  height:230px;
  width: 250px;
}

/* The end of the game recommendation boxes. */

方案2(不需要修改HTML,仅调整CSS)

直接给flex容器开启换行,强制标题独占一行即可:

.game-section{
  height: 400px; 
  width: 100%;
  background-color: darkkhaki;
  display: flex;
  flex-wrap: wrap; /* 允许子元素换行 */
  justify-content: center; /* 水平居中所有子元素 */
  align-content: flex-start; /* 内容从顶部开始排列 */
  padding-top: 20px;
}

/* 修正ID选择器 */
#games{
  width: 100%; /* 强制独占一行 */
  font-size: 23px;
  text-align: center;
  margin: 0 0 20px 0;
}

.box1{
background-color: darkolivegreen;
height:230px;
width: 250px;
display:inline-block;
margin: 20px;
 }

.box2{
background-color: rgba(108, 148, 39, 0.267);
height:230px;
width: 250px;
display: inline-block;
margin: 20px;
}

.box3{
background-color:rgb(104, 99, 26);
height:230px;
width: 250px;
display: inline-block;
margin: 20px;
}

/* The end of the game recommendation boxes. */

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 15:15:02