Html 如何在固定大小的 div 中水平居中按钮?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10173196/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to horizontally center the buttons in a fixed sized div?
提问by mahesh
Below is the code, two buttons in one div.
下面是代码,一个 div 中有两个按钮。
<div style="position:relative; width: 300px; height: 30px; border: 1px solid;">
<input type="button" value="ok" style="position:relative; width: 70px; height: 30px;">
<input type="button" value="ok" style="position:relative; width: 70px; height: 30px;">
</div>
How to horizontally center the buttons in fixed sized did ?
如何将固定大小的按钮水平居中?
回答by andyb
Adding text-align:center;
CSS to the <div>
will center the buttons. You should also consider separating the stylefrom the content, which amongst other reasons, reduces the duplication. For example
将text-align:center;
CSS添加到<div>
将按钮居中。您还应该考虑将样式与内容分开,这其中包括减少重复的原因。例如
CSS
CSS
div {
position:relative;
width:300px;
height:30px;
border:1px solid;
text-align:center;
}
input {
position:relative;
width:70px;
height:30px;
}
HTML
HTML
<div>
<input type="button" value="ok"/>
<input type="button" value="ok"/>
</div>
Edit:The official definition for text-align
states:
编辑:状态的官方定义text-align
:
The text-align property describes how inline-level content of a block container is aligned
text-align 属性描述了块容器的行内内容是如何对齐的
so it will centre allinline level elements and <input>
is an inline element.
所以它将所有内联级别元素居中并且<input>
是一个内联元素。
回答by dimmat
Try this:
尝试这个:
<div style="position:relative; width: 300px; height: 30px; border: 1px solid; text-align:center;">
<input type="button" value="ok" style="position:relative; width: 70px; height: 30px;">
<input type="button" value="ok" style="position:relative; width: 70px; height: 30px;">
</div>
回答by Shailender Arora
Give text-align:center;to your main div & don't need to use inline css we should define css classes through external CSSfiles and here we don't need any kind of positioning we can do easily by simple CSS
给text-align:center; 到您的主 div & 不需要使用内联 css 我们应该通过外部CSS文件定义 css 类,在这里我们不需要任何类型的定位,我们可以通过简单的CSS轻松完成
**CSS**
div {
width: 300px;
height: 30px;
border: 1px solid;
text-align:center;
}
.button {
width: 70px;
height: 30px;
}
HTML
HTML
<div>
<input type="button" value="ok" class="button">
<input type="button" value="ok" class="button">
</div>
demo :- http://jsbin.com/evomik/10/edit
回答by xholicka
<div style="position:relative; width: 300px; height: 30px; border: 1px solid;">
<div id="button_container" style="margin-left:auto; margin-right:auto;">
<input type="button" value="ok" style="position:relative; width: 70px; height: 30px;">
<input type="button" value="ok" style="position:relative; width: 70px; height: 30px;">
</div>
</div>