我有一个div,宽度为100%。

我想在其中居中一个按钮,我该怎么做呢?

< div风格= "宽度:100%;高度:100%;边框:1px实心"> <按钮type = "按钮" >你好> < /按钮 < / div >


当前回答

在div中居中按钮的响应方式:

<div 
    style="display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 2rem;">
    <button type="button" style="height: 10%; width: 20%;">hello</button>
</div>

其他回答

假设div是#div, button是#button:

#div {
    display: table-cell;
    width: 100%;
    height: 100%;
    text-align: center;
    vertical-align: center;
}

#button {}

然后像往常一样将按钮嵌套到div中。

响应式CSS选项,将按钮垂直和水平居中,而不考虑父元素大小(使用数据属性挂钩的清晰度和分离问题):

HTML

<div data-element="card">
  <div data-container="button"><button>CTA...</button></div>
</div>

CSS

[data-container="button"] {
  position: absolute;
  top: 50%;
  text-align: center;
  width: 100%;
}

小提琴:https://jsfiddle.net/crrollyson/zebo1z8f/

在div中居中按钮的响应方式:

<div 
    style="display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 2rem;">
    <button type="button" style="height: 10%; width: 20%;">hello</button>
</div>

适用于大多数情况的超级简单的答案是将margin设置为0 auto并将显示设置为block。你可以看到我在CodePen的演示中如何居中我的按钮

遇到这个,我想我也会留下我使用的解决方案,它利用line-height和text-align: center来做垂直和水平的居中:

点击这里使用JSFiddle