Evenly-spaced navigation links that take up entire width of ul in CSS3

▼魔方 西西 提交于 2019-12-18 17:56:22

问题


I'd like to create a horizontal navigation list of links, where the nav links are evenly spaced and take up the full width of the enclosing container <ul>. Nav links can be different widths. The first and last links should line up with the beginning and end of the <ul> respectively (meaning the links aren't centered), like this:

|left side..right side|

link1 link1 link3 link4

Unless I'm mistaken, I don't think there is a way to do this in CSS2. But is there a way to do it in CSS3? Otherwise I'll need to do it in Javascript.


回答1:


If you insist on CSS3, you can do it with box-flex. Since this isn't fully implemented in all browsers, the properties still have the -moz and -webkit prefixes.

Here's the CSS to do it:

ul {
  display: box;
}

li {
  box-flex: 1;
}

But since not all browsers use it, you have to add -moz-box-flex, -webkit-box-flex, etc.

Here's a demo: http://jsfiddle.net/tBu4a/9/




回答2:


That's straightforward to do with CSS2:

ul {
    display: table;
    width: 100%;
}
li {
    display: table-cell;
}
a {
    display: block;
}

Here's a working example. The problem isn't so much that CSS2 doesn't have a way to do it, it's that IE didn't fully support CSS2 until version 8.

--edit

OK, now I think I understand your requirements:

ul {
    display: table;
    width: 100%;
    border: 0;
    padding: 0;
    background-color: blue;
}
li {
    display: table-cell;
    border: 0;
    padding: 0;
    text-align: center;
}
li:first-child {
    text-align: left;
}
li:last-child {
    text-align: right;
}
a {
    display: block;
    padding: 0.25em 0;
    background-color: white;
    text-decoration: none;
}

Here it is in action. I've zeroed out all the borders and padding as per your comments, you could add some back in but you would, of course, need to zero out the left border/padding of the first link and the right border/padding of the right link using either li:first-child or li:first-child a (and the opposite last-child ones).



来源:https://stackoverflow.com/questions/6509183/evenly-spaced-navigation-links-that-take-up-entire-width-of-ul-in-css3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!