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

实现div横向并排及在div下方添加标题遇到问题求助

问题解决:导航面板横向排列+下方标题布局

问题根源分析

  1. div无法横向并排:.myDiv设置了display:block(块级元素默认独占一行),且父容器#topDivs用了display:table但未配合对应表格布局属性,导致子元素无法横向排列。
  2. 文本挤开div/换行无效:p标签自带默认上下外边距,会撑高.myDiv,同时之前的布局方式未明确控制元素流,导致文本与div布局冲突。
  3. HTML语法错误:第四个<a>标签存在语法错误,错误嵌套style属性写法,破坏了DOM结构。

修改后的完整代码

CSS部分

#topDivs {
  width: 100%;
  height: 50px;
  display: flex; /* 使用flex实现横向排列 */
}

.myDiv {
  border: 2px outset black;
  text-align: center;
  height: 50px;
  width: 25%;
  box-sizing: border-box;
  color: white;
  display: flex; /* 用于内部文本垂直居中 */
  justify-content: center;
  align-items: center;
}

.fill-div {
  height: 100%;
  width: 100%;
  text-decoration: none;
  background-color: transparent;
  display: flex;
  justify-content: center;
  align-items: center;
}

/* 移除p标签默认margin,避免撑高容器 */
.myDiv p {
  margin: 0;
}

#sec1 { background-color: darkred; }
#sec2 { background-color: rgb(112, 172, 76); }
#sec3 { background-color: rgb(252, 209, 42); }
#sec4 { background-color: skyblue; }

#mainText {
  border: 2px outset black;
  text-align: center;
  height: 50px;
  margin: 10px auto 0; /* 与上方导航拉开间距 */
  color: black; /* 改为黑色,默认白色无法看清 */
  display: flex;
  align-items: center;
  justify-content: center;
}

a:link, a:visited { color: white; }

HTML部分

<div id="maindiv">
  <!-- 顶部导航面板 -->
  <div id="topDivs">
    <div class="myDiv" id="sec1">
      <a href="index.html" class="fill-div">
        <p><strong>Index</strong></p>
      </a>
    </div>
    <div class="myDiv" id="sec2">
      <a href="interests.html" class="fill-div">
        <p><strong>Interests</strong></p>
      </a>
    </div>
    <div class="myDiv" id="sec3">
      <a href="education.html" class="fill-div">
        <p><strong>Education</strong></p>
      </a>
    </div>
    <div class="myDiv" id="sec4">
      <a href="contactme.html" class="fill-div">
        <p><strong>Contact me</strong></p>
      </a>
    </div>
  </div>

  <!-- 下方标题 -->
  <div id="mainText">
    <h2>页面标题</h2>
  </div>
</div>

<script src="script.js"></script>
<script src="https://replit.com/public/js/replit-badge.js" theme="blue" defer></script>

关键修改点说明

  • 父容器#topDivs改用display:flex,直接实现子元素横向等宽排列(每个.myDiv占25%宽度)。
  • 给.myDiv和.fill-div添加flex布局属性,确保内部文本垂直水平居中,同时移除margin:auto避免布局冲突。
  • 清除p标签默认margin,防止容器高度被撑高。
  • 修正第四个<a>标签的语法错误,移除无效的内联style写法。
  • 将#mainText放在#topDivs外部,自然处于导航下方,通过margin-top调整间距,同时修改文字颜色确保可见。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 17:30:12