我有一个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正在寻找水平和垂直中心,这个答案将做一个固定的宽度/高度元素。

其他回答

更新后的答案

更新是因为我注意到这是一个积极的答案,但现在Flexbox将是正确的方法。

现场演示

垂直和水平对齐。

#wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
}

只是水平(只要主伸缩轴是水平的,这是默认的)

#wrapper {
  display: flex;
  justify-content: center;
}

原来的答案使用固定宽度和不灵活

如果原来的海报想要垂直和中心对齐,它很容易固定宽度和高度的按钮,尝试以下

现场演示

CSS

button{
    height:20px; 
    width:100px; 
    margin: -20px -50px; 
    position:relative;
    top:50%; 
    left:50%;
}

对于水平对齐使用任何一种

button{
    margin: 0 auto;
}

or

div{
    text-align:center;
}

想起来:

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

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

由于提供了有限的细节,我将假设最简单的情况,并说你可以使用text-align: center:

http://jsfiddle.net/pMxty/

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

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

这是一个JS Bin的演示。

div { Text-align: center; } 按钮{ 宽度:50%; 保证金:1rem auto; } < div风格= "宽度:100%;高度:100%;边框:1px实心"> <按钮type = "按钮" >你好> < /按钮 < / div >

这是我经常做的事。 我认为bootstrap也在“mx-auto”中使用这个。