Evenly-spaced navigation links that take up entire

2020-02-29 10:48发布

问题:

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).