我想水平对齐按钮并将它们居中 css

I would like to horizontally align buttons and center them with css

我正在尝试将页面中央顶部的 4 个按钮与 css 水平对齐。这就是我的

button {
  background-color: rgb(243, 243, 243);
  border: 5px;
  color: #000000;
  padding: 15px 32px;
  text-align: center;
  margin: 4px 2px;
  cursor: pointer;
  -webkit-transition-duration: 0.6s;
  transition-duration: 0.6s;
  cursor: pointer;
  display: block;
  margin: auto;
}

每当我这样做时,按钮都会在中心对齐,但也会垂直对齐,它们应该是水平的。我已经试过了:

显示:内联块; 代替 显示:块;

但随后我的按钮水平对齐但不在页面顶部居中。

这就是你想要达到的目标吗??

将按钮放在容器内并对其应用 text-align:center

.container {
  text-align: center;
}

button {
  background-color: rgb(243, 243, 243);
  border: 5px;
  color: #000000;
  padding: 15px 32px;
  text-align: center;
  margin: 4px 2px;
  cursor: pointer;
  -webkit-transition-duration: 0.6s;
  transition-duration: 0.6s;
  cursor: pointer;
  /*margin: auto;*/
}
<div class='container'>
  <button>MyBtn1</button>
  <button>MyBtn1</button>
  <button>MyBtn1</button>
</div>

最好的方法是在容器中使用 text alig,如下所示:

.container {
  text-align: center;
}
 <div class='container'>
      <button>MyBtn1</button>
      <button>MyBtn1</button>
      <button>MyBtn1</button>
 </div>

有两种选择。在这两种情况下,您都需要将按钮包装在 divnav 或其他元素中。然后,您可以使用 display: inline-blockdisplay: flex 来布置它们。 inline-block 选项是传统方法,占用较少 CSS。如果您对将页面缩放到所有视口尺寸(即响应式设计)感兴趣,flex 是更好的选择。

显示:inline-block

button {
  background-color: #ccc;
  display: inline-block;
  margin: 5px;
}
nav {
  text-align: center
}
<nav>
  <button>Button 1</button>
  <button>Button 2</button>
  <button>Button 3</button>
  <button>Button 4</button>
</nav>

显示:弹性

button {
  background-color: #ccc;
  margin: 5px;
}
nav {
  display: flex;
  flex-direction: row;
  justify-content: center;
}
<nav>
  <button>Button 1</button>
  <button>Button 2</button>
  <button>Button 3</button>
  <button>Button 4</button>
</nav>