Divs在父块中对齐

时间:2011-03-19 11:10:26

标签: css html alignment

#Menu
{
    position: relative;
    width: 90%;
    margin: 0 auto;
    height; 50px;
    min-height: 50px;
    padding: 5px;
}

儿童阻拦:

#MenuItem
{
    position: relative;
    float: left;

    margin: 0 auto;
    margin-top: 2px;
    margin-left: 5px;
    margin-right: 5px;

    text-align: center;
    width: 142px;
    height: 37px;
}

和html:

    <div id="Menu">
        <div id="MenuItem"><span>Home</span></div>
        <div id="MenuItem"><span>Home</span></div>
        <div id="MenuItem"><span>Home</span></div>
    </div>

如何使MenuItem div在父div中水平对中?

2 个答案:

答案 0 :(得分:1)

<ul id="nav">
  <li><a href="/">Home</a></li>
  <li><a href="/about/">About</a></li>
  <li><a href="/work/">Work</a></li>
  <li><a href="/clients/">Clients</a></li>
  <li><a href="/contact/">Contact</a></li>
</ul>

这是css

#nav{
  border:1px solid #ccc;
  border-width:1px 0;
  list-style:none;
  margin:0;
  padding:0;
  text-align:center;
}
#nav li{
  display:inline;
}
#nav a{
  display:inline-block;
  padding:10px;
}

答案 1 :(得分:0)

以下代码应该这样做

#Menu
{
    position: relative;
    width: 90%;
    margin: 0 auto;
    height; 50px;
    min-height: 50px;
    padding: 5px;
    text-align: center; /* added this rule */
}

#MenuItem
{
    position: relative;
    display: inline-block;  /* changed from float:left */

    margin: 0 auto;
    margin-top: 2px;
    margin-left: 5px;
    margin-right: 5px;

    text-align: center;
    width: 142px;
    height: 37px;
}

另外,我建议你使用

<ul id="Menu">
  <li>...</li>
  <li>...</li>
</ul>

而不是嵌套的div。