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

如何让响应式侧边栏菜单的导航元素在大屏幕下顶部居中

修改后完整代码

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
body {
  margin: 0;
  font-family: "Lato", sans-serif;
}

.sidebar {
  margin: 0;
  padding: 0;
  width: 200px;
  background-color: #f1f1f1;
  position: fixed;
  height: 100%;
  overflow: auto;
}

.sidebar a {
  display: block;
  color: black;
  padding: 16px;
  text-decoration: none;
  /* 新增:宽屏侧边栏菜单项文字水平居中 */
  text-align: center;
}
 
.sidebar a.active {
  background-color: #04AA6D;
  color: white;
}

.sidebar a:hover:not(.active) {
  background-color: #555;
  color: white;
}

div.content {
  margin-left: 200px;
  padding: 1px 16px;
  height: 1000px;
}

@media screen and (max-width: 700px) {
  .sidebar {
    width: 100%;
    height: auto;
    position: relative;
  }
  .sidebar a {
    float: left;
    /* 新增:横向菜单栏时恢复文字左对齐,可根据需求调整为center */
    text-align: left;
  }
  div.content {margin-left: 0;}
}

@media screen and (max-width: 400px) {
  .sidebar a {
    text-align: center;
    float: none;
  }
}
</style>
</head>
<body>

<div class="sidebar">
  <a class="active" href="#home">Home</a>
  <a href="#news">News</a>
  <a href="#contact">Contact</a>
  <a href="#about">About</a>
</div>

<div class="content">
  <h2>响应式侧边栏示例</h2>
  <p>该示例通过媒体查询实现:当屏幕宽度小于等于700px时,侧边栏会变为顶部横向导航栏。</p>
  <p>同时针对宽度小于等于400px的屏幕做了额外适配,导航链接会垂直堆叠且居中显示。</p>
  <h3>调整浏览器窗口大小即可查看效果。</h3>
</div>

</body>
</html>

调整说明

  • 仅新增了两行CSS代码,完全保留原有响应式逻辑:
    1. 给默认状态的.sidebar a添加text-align: center,实现宽屏侧边栏纵向排列时,菜单项在侧边栏内水平居中
    2. 在700px宽度的媒体查询中给.sidebar a添加text-align: left,保证中屏横向菜单栏的文字对齐方式符合原有设计,如果你希望中屏横向菜单的文字也居中,把这个值改成center即可

内容的提问来源于stack exchange,提问作者Omar Elio Torres Castillo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 22:06:03