如何在 div 中使按钮居中或对齐?

3
我正在创建一个包含多个按钮的 div。
<div>
    <button>a</button><button>b</button>
</div>

我希望按钮能出现在div中间或居中显示。多行按钮应该基本上看起来像文本,但是居中/对齐。

像这样的吗?http://jsfiddle.net/vd7xx/ 您应该绘制一张图片来展示您需要什么。 - singe3
类似这样的吗?http://stackoverflow.com/questions/24245616/vertically-centering-content-in-html/24245798#24245798 - Joffrey Maheo
8个回答

3

如果需要垂直显示此按钮,则使用flex-direction: column;,如果需要水平显示,则使用flex-direction: row;。并将此属性添加到您的代码中。

div{
  position:relative;
  display:flex;
  flex-direction: column;
  flex-wrap:wrap;
}

button{
  display:block;
  padding:1rem 2rem;
  background:#d0333a;
  margin-bottom:.5rem;
  text-align:center;
  border: none;
  border-radius:6px;
  color:#fff;
  cursor:pointer;
}
<div>
  <button>a</button><button>b</button><button>c</button><button>d</button>
</div>


2

请使用以下内容:

<button style="margin: 0 auto; display: block;">a</button>
<button style="margin: 0 auto; display: block;">b</button>

1
如果您没有指定宽度,margin:auto将不起作用。 - singe3
谢谢您的建议,但实际上它已经在工作了。 - Leo
你可以检查这个链接:http://jsfiddle.net/L8u34/...,使用和不使用margin:auto。 - Leo

1
您可以使用CSS属性。
text-align: center;

这可以用于居中所有内联元素,如按钮、文本等...


0

只需使用text-align:center

<div style="text-align:center">
    <button>a</button><button>b</button>
</div>

敬礼, Nimesh P.


0
<style>
div{
   text-align: center;
}
</style>

它将会执行...


0
如果您有一个按钮作为块级元素或任何其他块级元素,您可以这样做:
<div class="container">
    <button>button</button>
</div>

和 CSS

.container { width: 100%;}
.container button { display: block; margin: 0 auto;}

0

演示

html

<div>
    <button>a</button><button>b</button><button>c</button><button>d</button><button>e</button><button>f</button><button>g</button><button>h</button>
</div>

CSS

div{
    text-align: center;
}
button {
    background: transparent;
    border: none;
    cursor: pointer;
    padding: 5px;
}

0

为了在水平和垂直方向上对齐按钮,请将以下内容应用于父DIV

HTML

<div id = "parent_div">
 <button>a</button>
 <button>b</button>
 <button>c</button>
</div>

CSS

#parent_div {
 width:200px;
 height:200px;
 border:solid 1px blue;
 display:flex;/*Requires vendor prefixes*/
 justify-content:center;/*Requires vendor prefixes*/
 align-items:center;/*Requires vendor prefixes*/
}

演示

删除 justify-contentalign-items 以去除垂直和水平对齐。

阅读此文:FLEX


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接