Border too wide because of margin

2019-09-01 07:42发布

问题:

I have an inline unordered list as navigation bar in my html. I wanted a top border to show up when hovering on li element. But when I add margin or padding to make some space between consecutive elements, the border is too wide. I don't want to add spaces in html. Is there any other way? I tried putting an empty div with defined width but it didn't work. The best result I could get was with text-decoration overline, but unfortunately i need a different color than black. Here's my code:

LI
{
display: inline;
font-family: Arial;
font-size: 16px;
font-weight: bold;
text-transform: uppercase;
letter-spacing: 0.2em;
padding-left: 30px;
}
LI:hover
{
border-top: 1px solid #000000;
}

and HTML

<ul>
            <a href="#"><li>link 1</li></a>
            <a href="#"><li>link 2</li></a>
            <a href="#"><li>link 3</li></a>
            <a href="#"><li>link 4</li></a>
</ul>

回答1:

Padding extends the width of your elements while margin creates empty spacing after and before the element. You may want to read more about Box Model.

I adjusted my code to better suit your case:

HTML:

<ul>
    <a href="#"><li>link 1</li></a>
    <a href="#"><li>link 2</li></a>
    <a href="#"><li>link 3</li></a>
    <a href="#"><li>link 4</li></a>
</ul>

CSS:

ul a {
    text-decoration: none !important; //Removes default underline form link
}

li {
    display: inline;
    font-family: Arial;
    font-size: 16px;
    font-weight: bold;
    text-transform: uppercase;
    letter-spacing: 0.2em;
    padding-left: 0.2em; // Letter spacing is making borders to extend slightly more on the right. This makes borders extend similarly on the left
    padding-top: 2px; //To push top border slightly higher, so that top and bottom is the same distance from your text
    margin-left: 30px;
    text-align: center;
    border-top: 1px solid transparent; //Stops navigation from extending on :hover
}

li:hover {
    border-top: 1px solid #000; //border top on :hover
}

FiddleJS: http://jsfiddle.net/kGN69/2/



回答2:

Instead of using margin, try using Padding instead.

Can I see your coding...? It would be a lot easier.

First, are you making sure you are editing the li hover?

Example:

#yourdiv li a:hover{
.....
}

If you are, try change this.

Example:

#yourdiv{
...
padding-top:5px;
padding-bottom:5px;
padding-right:5px;
padding-left:5px;
}