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

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

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


当前回答

想起来:

button {
  width: 100px; // whatever your button's width
  margin: 0 auto; // auto left/right margins
  display: block;
}

更新:如果OP正在寻找水平和垂直中心,这个答案将做一个固定的宽度/高度元素。

其他回答

在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的演示中如何居中我的按钮

你应该把它简单化:

首先你有你的文本或按钮的初始位置:

<div style="background-color:green; height:200px; width:400px; margin:0 0 0 35%;">
   <h2> Simple Text </h2>
      <div>
           <button> Simple Button </button>
      </div>
</div>

通过将此css代码行添加到h2标记或包含按钮标记的div标记

样式:" text-align:center; "

结果代码将是:

<div style="background-color:green; height:200px; width:400px; margin:0 0 0 35%;">
<h2 style="text-align:center;"> Simple Text </h2> <!-- <<--- here the changes -->

      <div style="text-align:center">        <!-- <<--- here the changes -->
                <button> Simple Button </button>
      </div>
</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/

要将<button type = "button">在<div>中垂直和水平居中,宽度是动态计算的,就像在你的例子中一样,下面是要做的:

设置文本对齐:居中;到换行<div>:当你调整<div>(或者窗口)的大小时,这将使按钮居中。 对于垂直对齐,你需要设置margin: valuepx;对于按钮。下面是计算valuepx的规则: valuepx = (wrappingDIVheight - buttonHeight)/2

这是一个JS Bin的演示。