我有一个宽度为100%的div。
我想把一个按钮放在里面,我该怎么办?
<div style="width:100%; height:100%"> <button type="button">hello</button> </div>I have a div that's width is 100%.
I'd like to center a button within it, how might I do this?
<div style="width:100%; height:100%"> <button type="button">hello</button> </div>最满意答案
更新答案
更新,因为我注意到这是一个积极的答案,但是Flexbox现在将是正确的方法。
现场演示
垂直和水平对齐。
#wrapper { display: flex; align-items: center; justify-content: center; }只是水平(只要主弯轴是水平的,这是默认的)
#wrapper { display: flex; justify-content: center; }原始答案使用固定的宽度和没有flexbox
如果原始的海报想要垂直和中心对齐,那么它对于按钮的固定宽度和高度来说很容易,请尝试以下操作
现场演示
CSS
button{ height:20px; width:100px; margin: -20px -50px; position:relative; top:50%; left:50%; }也可以使用水平对齐
button{ margin: 0 auto; }要么
div{ text-align:center; }Updated Answer
Updating because I noticed it's an active answer, however Flexbox would be the correct approach now.
Live Demo
Vertical and horizontal alignment.
#wrapper { display: flex; align-items: center; justify-content: center; }Just horizontal (as long as the main flex axis is horizontal which is default)
#wrapper { display: flex; justify-content: center; }Original Answer using a fixed width and no flexbox
If the original poster wants vertical and center alignment its quite easy for fixed width and height of the button, try the following
Live Demo
CSS
button{ height:20px; width:100px; margin: -20px -50px; position:relative; top:50%; left:50%; }for just horizontal alignment use either
button{ margin: 0 auto; }or
div{ text-align:center; }更多推荐
button,width,div,电脑培训,计算机培训,IT培训"/> <meta name="description&
发布评论