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

CSS新手求助:如何让带按钮的边框容器横向并排?

解决按钮组容器横向并排的问题

方案:使用Flexbox布局(推荐)

Flexbox是现代CSS布局方案,能轻松实现元素横向排列与居中,比float更简洁可控。

修改步骤:

  1. 给按钮组添加外层容器:把两个带边框的按钮组包裹在一个容器内,通过Flex布局控制排列方式。
  2. 合并重复CSS类:.border和.border-2样式完全一致,合并为.button-group减少冗余代码。
  3. 调整间距与居中:用Flex的justify-content实现整体居中,通过gap控制两个按钮组的间距。

修改后的完整代码:

html,
body {
  font-family: Arial, Sans-Serif;
  text-align: center;
  padding: 20px;
}

/* 外层容器:控制两个按钮组横向排列 */
.button-groups-container {
  display: flex;
  justify-content: center;
  gap: 20px; /* 两个按钮组之间的间距 */
}

.button {
  background-color: #04AA6D;
  border: none;
  color: white;
  padding: 15px 32px;
  margin: auto;
  display: block;
  font-size: 16px;
  cursor: pointer;
  margin-bottom: 10px;
}

.button:hover {
  background-color: #038253;
}

/* 合并后的按钮组样式 */
.button-group {
  border: 3px solid black;
  padding: 10px;
  width: 150px;
  margin-top: 20px;
}
<h1>Test Site</h1>
<!-- 外层容器 -->
<div class="button-groups-container">
  <!-- Button Group 1 -->
  <div class="button-group">
    <button type="button" class="button" onclick="window.open('https://example.com')">Button 1</button>
    <button type="button" class="button" onclick="window.open('https://example.com')">Button 2</button>
    <button type="button" class="button" onclick="window.open('https://example.com')">Button 3</button>
  </div>

  <!-- Button Group 2 -->
  <div class="button-group">
    <button type="button" class="button" onclick="window.open('https://example.com')">Button 1</button>
    <button type="button" class="button" onclick="window.open('https://example.com')">Button 2</button>
    <button type="button" class="button" onclick="window.open('https://example.com')">Button 3</button>
  </div>
</div>

为什么float没生效?

你之前用float失败的原因:

  • 块级元素默认占满一行,float后虽能并排,但margin: auto对浮动元素无效,导致容器无法居中只能贴边。
  • float需要手动清除浮动,否则会影响后续元素布局,操作繁琐,Flexbox则无需处理这些问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 06:13:33