Border too wide because of margin

℡╲_俬逩灬. 提交于 2019-12-25 10:53:27

问题


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;
}


来源:https://stackoverflow.com/questions/17330456/border-too-wide-because-of-margin

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