日期:2014-05-17  浏览次数:20673 次

怎么实现水平方向中间对齐?
我经常看到有人说margin-left和margin-right设置为auto就能水平方向中间对齐。
或者设置center里面的内容就能对齐。
能给我解释解释margin-left和margin-right设置为auto,align设置为center和center标签的水平方向对齐有什么不一样吗?
为什么我下面这个例子我用了这么多对齐方式它就是不水平方向中间对齐呢?

<div class="content" style="clear:both; min-height: 70%; margin:0 auto; padding:0px; position:absolute;top:90px;z-index:-1;">
  <center>
  <table style="margin:auto; width:50%;">
  <form action="">
  <tr>
  <td>房间号:</td><td><input type="text" name="roomid"></input></td>
  </tr>
  <tr>
  <td>空调:</td><td><select name="air-conditioner">
  <option value="nornal">正常</option>
  <option value="none">无</option>
  <option value="broken">坏</option>
  <option value="maintenance">维修中</option>
  </select></td>
  </tr>
  <tr>
  <td><input type="submit" value="创建房间"></input></td>
  </tr>
  </form>
  </table>
  </center>
</div>

------解决方案--------------------
一般块级元素用margin: 0 auto;居中
元素中文本用text-align:center;居中
------解决方案--------------------
要同时用margin: 0 auto和padding:0 auto
你用的什么浏览器?换着IE和Firefox对照一下应该有个是水平居中的

------解决方案--------------------
用text-align=center
------解决方案--------------------
table中间对齐,不需要在外面加div,只要<table align="center">它就相对于容器中间对齐了。别的我没试过。反正都有办法对齐。
其他对齐各浏览器有差异,得分开测试。
------解决方案--------------------
margin:0 auto; 就能居中了,当然,你本层宽度要小于上一层才能看到效果。
------解决方案--------------------
有时候,必须定义width, margin:0 auto;才会生效
------解决方案--------------------
看看csdn论坛,本页面的源码。
body的
#bbscsdn_wrap {
background: white;
width: 960px;
margin: 0 auto;
}

------解决方案--------------------
因为你用了absolute
------解决方案--------------------
不设置width;margin 都没有作用的
------解决方案--------------------
因为你用了position:absolute 所以你只能使用left去实现水平居中了。
------解决方案--------------------
探讨
引用:

因为你用了position:absolute 所以你只能使用left去实现水平居中了。

left指什么?