【问题标题】:I would like to horizontally align buttons and center them with css我想水平对齐按钮并将它们与css居中
【发布时间】:2018-08-11 14:57:59
【问题描述】:

我正在尝试将页面中心顶部的 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;
}

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

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

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

【问题讨论】:

  • 你能提供你的 html 标记吗?你的按钮是使用div 还是button 标签。

标签: html css button alignment center


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

    将按钮放置在容器内,然后对其应用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>

    【讨论】:

    • 谢谢!好久没编程了,帮帮我,谢谢!
    【解决方案3】:

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

    显示:内联块

    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>

    【讨论】:

    • 我认为你不需要flex-direction: row,因为button 标签是一个内联元素。
    • @SahinErbay,谢谢! flex-direction 也默认为 row,所以它是双重不必要的。我只是想稍微充实一下 flex-box 模型,以防它不熟悉。
    猜你喜欢
    • 2019-01-11
    • 2014-04-20
    • 2010-11-10
    • 2016-02-20
    • 2016-04-23
    • 1970-01-01
    • 2019-10-09
    • 2013-11-15
    • 2020-08-07
    相关资源
    最近更新 更多