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

如何借助Bootstrap实现指定宽度的ul列表居中显示?

实现Bootstrap下UL列表居中及指定宽度列表居中的方案

嘿,我来帮你搞定这个列表居中的问题!用Bootstrap的内置工具类就能轻松实现,咱们一步步来调整你的代码:

方案1:纵向排列的列表(UL整体居中,LI固定宽度)

这种情况适合列表项垂直排列,同时让整个UL容器和内部固定宽度的LI都居中显示:

调整后的HTML代码

<body>
  <h1 class="text-center text-white">MENU</h1>
  <!-- 用Bootstrap的mx-auto让UL自身居中,无需额外外层容器 -->
  <ul id="list" class="p-0 mx-auto">
    <li class="list-unstyled my-2 text-center">
      <a href="#" class="text-white">text_1</a>
    </li>
    <li class="list-unstyled my-2 text-center">
      <a href="#" class="text-white">text_2</a>
    </li>
    <li class="list-unstyled my-2 text-center">
      <a href="#" class="text-white">text_3</a>
    </li>
    <li class="list-unstyled my-2 text-center">
      <a href="#" class="text-white">text_4</a>
    </li>
    <li class="list-unstyled my-2 text-center">
      <a href="#" class="text-white">text_5</a>
    </li>
  </ul>
</body>

优化后的CSS代码

body {
  background-color: rgb(26, 40, 114);
}

h1 {
  color: white;
  text-shadow: 7px 7px 10px black;
}

li {
  border-radius: 5px;
  border: 2px solid white;
  background-color: black;
  padding: 7px;
  width: 200px;
}

/* 给UL设置固定宽度,和LI保持一致,确保内部内容对齐 */
#list {
  width: 200px;
}

关键说明:

  • 用Bootstrap的mx-auto类给UL设置左右自动边距,实现UL整体水平居中
  • list-unstyled替代自定义的list-style: none,p-0清除默认内边距
  • my-2给每个LI添加上下间距,提升美观度
  • text-center让LI内部的链接文字居中显示

方案2:横向排列的列表(LI自动换行,整体居中)

如果希望列表项横向排列,超出宽度自动换行,同时整个列表保持居中:

调整后的HTML代码

<body>
  <h1 class="text-center text-white">MENU</h1>
  <ul id="list" class="d-flex flex-wrap justify-content-center p-0 gap-3">
    <li class="list-unstyled text-center">
      <a href="#" class="text-white">text_1</a>
    </li>
    <li class="list-unstyled text-center">
      <a href="#" class="text-white">text_2</a>
    </li>
    <li class="list-unstyled text-center">
      <a href="#" class="text-white">text_3</a>
    </li>
    <li class="list-unstyled text-center">
      <a href="#" class="text-white">text_4</a>
    </li>
    <li class="list-unstyled text-center">
      <a href="#" class="text-white">text_5</a>
    </li>
  </ul>
</body>

CSS代码保持不变(仅需保留你的原有LI样式)

body {
  background-color: rgb(26, 40, 114);
}

h1 {
  color: white;
  text-shadow: 7px 7px 10px black;
}

li {
  border-radius: 5px;
  border: 2px solid white;
  background-color: black;
  padding: 7px;
  width: 200px;
}

关键说明:

  • d-flex把UL变成弹性容器,让LI横向排列
  • flex-wrap实现超出宽度自动换行
  • justify-content-center让弹性容器内的LI整体水平居中
  • gap-3给LI之间添加上下左右间距(替代自定义margin,更简洁)

这两种方案都充分利用了Bootstrap的工具类,减少自定义CSS的编写,同时完美实现你要的居中效果~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 07:09:42