如何将一个按钮放在一个div内?(How to center a button within a div?)

编程入门 行业动态 更新时间:2024-10-27 02:18:03
如何将一个按钮放在一个div内?(How to center a button within a div?)

我有一个宽度为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&

本文发布于:2023-07-20 11:07:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1198676.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:放在   如何将   按钮   button   div

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!