Unordered list navigation with floating left and r

2019-08-20 01:27发布

问题:

I have a simple navigation bar at the top of the page with several links – the first is floated to the left using li:first child, the last floated to the right using li:last child, with the remainder centered in the middle of the page.

To all intents and purposes this works – but although the space between each of the navigation blocks is the same, the central block is actually positioned much further to the right. I presume this is because the links differ in length – ie 23 characters for link 1, 7 characters for link 2.

Is there any way of resolving this, or should I be using another approach to position the middle block in the absolute centre of the page?

Below is the code that I am currently working with, and a jsfiddle can be found here: http://jsfiddle.net/pxuVJ/

EDIT 19:28 13.05.12 As it is a little confusing to explain, I've taken a screengrab which illustrates the problem: http://bit.ly/Khd8cN

Many thanks.

HTML:

<nav>
<div id="navigation">
<ul>
    <li><a href="#home">title of site</a></li>
    <li><a href="#link 1">link 1</a></li>
    <li>&#8226;</li>
    <li><a href="#link2">link 2</a></li>
    <li>&#8226;</li>
    <li><a href="#link 3">link3</a></li>
    <li><a href="#contact">contact</a></li>
</ul>
</div>
</nav>

CSS:

nav {
font: 10pt Courier;
position: fixed;
top: 0; right: 0; bottom: 0; left: 0;
height: 20px;
padding: 20px;
background-color: #ffffff;
text-transform: uppercase;
z-index: 10;
text-align: center;
}

nav li { display: inline; list-style: none; }
nav li:first-child { float: left; }
nav li:last-child { float: right; }​

回答1:

instead of using

dispaly:inline;

you can use

nav li { float:left; list-style: none; padding : 10px; }
nav li:first-child { margin-right:50px; } nav li:last-child { margin-left:50px; }


回答2:

Shreedhar is quite right in that using 'float' is not required – although rather than guessing the margins assigning li:first-child and li:last child absolute positions seems to be a better method – it also seems to work with any number of links in the central block.

nav li {
    display: inline;
    list-style: none;
    text-align: center;
}

nav li:first-child {
    position: absolute;
    left: 20px;
    text-align:left;
}

nav li:last-child {
    position: absolute;
    right: 20px;
    text-align: right;
}