问题
When hovering a link I want it to get an underline. The underline should be 2px strong and 4px below the text.
With
text-decoration: underline
I get a 1px strong line which is 4px below. (Distances vary by font)
If I write
border-bottom: 2px solid #000;
I get a 2px line which is about 10px below the text.
How can I decrease the distance between the text and the border?
padding-bottom: -6px
does not work. Any negative value with padding-bottom does not work.
Or how can i get the underline to be 2px strong?
http://jsfiddle.net/qJE2w/1/
回答1:
One quick solution that comes into my mind is to apply the border on a pseudo-element:
.border{
position: relative;
}
.border:hover::after{
content:'';
position:absolute;
width: 100%;
height: 0;
left:0;
bottom: 4px; /* <- distance */
border-bottom: 2px solid #000;
}
(example)
回答2:
You can use line-height for decrease distance.
.underline {
display: inline-block;
line-height: 0.9; // the distance
border-bottom: 1px solid;
}
Drawback of this method -- because we use block display it works only for single line of the text.
回答3:
Multi line solution
Explanation. I'm creating a sibling which has the same text and text style and is shifted to top a bit. If you want to keep your code clean you can insert the sibling using JS on a page load event.
Restrictions. This solution doesn't work inside paragraph of text.
.underlined_link {
text-decoration: none;
display: inline;
}
.underlined_link h2,
.underlined_link div {
display: inline;
font-size: 20px;
margin: 0;
line-height: 35px;
font-weight: normal;
padding: 0;
}
.underlined_link h2 {
color: transparent;
border-bottom: 1px solid red;
}
.underlined_link div {
position: absolute;
top: 10px;
left: 8px;
}
<a class="underlined_link" href="#">
<h2>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean eu nulla vel massa efficitur lacinia. In at dolor ac nulla interdum convallis. Nullam vitae eros orci. Curabitur vitae maximus erat, vel pulvinar ex.</h2>
<div><span>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean eu nulla vel massa efficitur lacinia. In at dolor ac nulla interdum convallis. Nullam vitae eros orci. Curabitur vitae maximus erat, vel pulvinar ex.</span></div>
</a>
回答4:
You can use background
with linear-gradient
to produce a border, and with it you can position it anywhere.
For example:
background-image: linear-gradient(currentColor, currentColor);
background-position: 0 94%;
background-repeat: no-repeat;
background-size: 0;
http://jsfiddle.net/1mg4tkwx/
Credit: https://www.dannyguo.com/blog/animated-multiline-link-underlines-with-css/
回答5:
This Line works for me:
.main-nav ul li {
padding: 0 10px;
}
.main-nav .main-menu li a {
border-right: 2px solid #262626;
padding: 7px;
}
来源:https://stackoverflow.com/questions/14733011/css-decrease-space-between-text-and-border