【问题标题】:Center ul in div vertically and horizontally将 ul 在 div 中垂直和水平居中
【发布时间】:2011-10-25 15:18:48
【问题描述】:

有人可以根据下面的代码帮助我将“div”中的“ul”垂直和水平居中吗?

非常感谢!

<div id="nav">
  <ul>
    <li><a class="top" href="#top"><span></span></a></li>
    <li><a class="bottom" href="#bottom"><span></span></a></li>
    <li><a>Link 1</a></li>
    <li><a>Link 2</a></li>
  </ul>
</div>

css

#nav {
    height:35px;
    border-bottom:1px solid #ddd;
    position:fixed;
    top:0px;
    left:0px;
    right:0px;
    background:#fff url(../images/navigation/nav.png) repeat-x center left;
    z-index:999999;
}

#nav ul {
    list-style:none;
    margin:auto;
    float:left;
    padding:0;
    display: block;
}

#nav ul li {
    display:inline;
    float:left;
    margin:0px 2px;
}

#nav a {
    font-size:13px;
    font-weight:bold;
    float:left;
    padding: 2px 4px;
    color:#999;
    text-decoration: none;
    border:1px solid #ccc;
    cursor: pointer;
    background:transparent url(../images/navigation/overlay.png) repeat-x center left;
    height:16px;
    line-height:16px;
}

#nav a:hover {
    background:#D9D9DA none;
    color: #fff;
}

#nav a.top span, #nav a.bottom span {
    float:left;
    width:16px;
    height:16px;
}

#nav a.top span {
    background:transparent url(../images/navigation/top.png) no-repeat center center;
}

#nav a.bottom span {
    background:transparent url(../images/navigation/bottom.png) no-repeat center center;
}

【问题讨论】:

  • 你不能将 "float: left" 和 "margin: auto" 组合在一起,它们只会在左侧结束,在 "#nav ul" 中测试以替换 "float: left" whit "宽度:200px;边框:纯红色 1px;"然后它居中

标签: html css center


【解决方案1】:

display: inline-blocktext-align: center 结合使用。这很好,因为如果您添加或删除链接,它将继续工作。

见:http://jsfiddle.net/thirtydot/VCZgW/

我所做的重要更改:

#nav {
    /*height:35px;*/
    padding: 6px 0;
}
#nav ul {
    /*float:left;*/
    text-align: center;
}
#nav ul li {
    /*float:left;*/
    vertical-align: top;
    display: inline-block;
}

【讨论】:

    【解决方案2】:

    这不会直接解决您的问题,但这些是我的 css 居中问题链接

    横向

    http://dorward.me.uk/www/centre/

    垂直

    http://phrogz.net/css/vertical-align/index.html

    【讨论】:

      【解决方案3】:

      正确的做法是:

      你把风格放在ul {display:table; margin:0 auto;}

      就是这样;)

      【讨论】:

      • 这只是水平居中
      • 水平和垂直,但如果它只对你来说是水平的,那意味着你离开了这个:#nav ul li { /*float:left;*/ vertical-align: top; }你正在把它变成一个表格,表格单元格是居中的hor和vert,但是如果你定义@987654323 @它将转到顶部、中间或中心取决于您的选择。
      猜你喜欢
      • 2014-07-03
      • 2015-08-29
      • 1970-01-01
      • 2014-11-22
      • 2015-09-16
      • 2012-12-16
      • 2013-10-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多