如何创建一个水平菜单,每个项目之间的宽度和间距相等? [英] How can I create a horizontal menu with each item being equal width and spacing inbetween?

查看:10
本文介绍了如何创建一个水平菜单,每个项目之间的宽度和间距相等?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我到目前为止所得到的:fiddle

Here's what I've got so far: fiddle

虽然有 2 个问题:

  1. 我已将每个 li 的宽度硬编码为 33%,我不想这样做,以便可以轻松添加更多项目.
  2. 我想在每个项目之间放置一些间距(背景颜色的间隙),但是一旦我添加边距,一个项目就会被撞到一行.我该如何解决?
  1. I've hard-coded the width of each li to 33%, which I'd prefer not to do so that I can easily add more items.
  2. I want to put some spacing between each item (a gap in the background color), but as soon as I add a margin, one item will be bumped down a line. How do I get around that?

#main-nav {
    list-style: none;
    margin: 0;
    padding: 0;
    width: 100%;
    overflow:  auto;
}
#main-nav li {
    float: left;
    width: 33%;
    height: 25px;
    text-align: center;
}
#main-nav li a {
    width: 100%;
    display: block;
    height: 100%;
    line-height: 25px;
    text-decoration: none;
    background-color: #e0e0f0;
    font-weight: bold;
    color: #021020;
}
#main-nav li a:hover {
    background-color: #498cd5;
    color: #ddeeee;
}

<ul id="main-nav">
    <li><a href="#">one</a></li>
    <li><a href="#">two</a></li>
    <li><a href="#">three</a></li>
</ul>

推荐答案

参见: http://jsfiddle.net/f6qmm/

display: table 被用来均匀分布动态数量的 li.不幸的是,在 IE7 中不起作用,所以 *float: left使用(仅适用于 IE7 及更低版本),因此至少它们都在一条线上 - 尽管它看起来仍然很可怕.

display: table is being used to evenly space a dynamic number of lis. Unfortunately, that doesn't work in IE7, so *float: left is used (for only IE7 and lower) so that at least they're all on one line - though it still looks horrendous.

padding-left: 5px 应用于每个 li,然后 li:first-child { padding-left: 0 } 将其移除仅适用于第一个 li.

padding-left: 5px is applied to every li, then li:first-child { padding-left: 0 } removes it for only the first li.

#main-nav {
    list-style: none;
    margin: 0;
    padding: 0;
    width: 100%;
    display: table;
    table-layout: fixed;
    overflow: hidden
}
#main-nav li {
    display: table-cell;
    *float: left; /* improve IE7 */
    height: 25px;
    text-align: center;
    padding-left: 5px
}
#main-nav li:first-child {
    padding-left: 0
}
#main-nav li a {
    width: 100%;
    display: block;
    height: 100%;
    line-height: 25px;
    text-decoration: none;
    background-color: #e0e0f0;
    font-weight: bold;
    color: #021020;
}
#main-nav li a:hover {
    background-color: #498cd5;
    color: #ddeeee;
}

<ul id="main-nav">
    <li><a href="#">one</a></li>
    <li><a href="#">two</a></li>
    <li><a href="#">three</a></li>
</ul>

<hr />

<ul id="main-nav">
    <li><a href="#">one</a></li>
    <li><a href="#">two</a></li>
    <li><a href="#">three</a></li>
    <li><a href="#">four</a></li>
    <li><a href="#">five</a></li>
</ul>

这篇关于如何创建一个水平菜单,每个项目之间的宽度和间距相等?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆