繁体   English   中英

如何在固定大小的div中水平居中按钮?

[英]How to horizontally center the buttons in a fixed sized 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>

如何将固定尺寸的按钮水平居中?

添加text-align:center; CSS中的<div>将按钮居中。 您还应该考虑将样式内容分开, 除其他原因外 ,还可以减少重复。 例如

CSS

div {
    position:relative;
    width:300px;
    height:30px;
    border:1px solid;
    text-align:center;
}

input {
    position:relative;
    width:70px;
    height:30px;
}

HTML

<div>
    <input type="button" value="ok"/>
    <input type="button" value="ok"/>
</div>

编辑: text-align状态的官方定义

text-align属性描述了块容器的内联级内容是如何对齐的

所以它将居中所有内联级别元素, <input>是一个内联元素。

试试这个:

<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>

给出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

<div>
<input type="button" value="ok" class="button">
<input type="button" value="ok" class="button">
</div>

演示: - http://jsbin.com/evomik/10/edit

<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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM