14

悬停链接时,我希望它有下划线。下划线应在文本下方 2px 和 4px 处。

text-decoration: underline

我得到一条 1px 的强线,低于 4px。(距离因字体而异)

如果我写

border-bottom: 2px solid #000;

我得到一条 2px 的线,它在文本下方约 10px 处。

如何减少文本和边框之间的距离?

padding-bottom: -6px

不起作用。padding-bottom 的任何负值都不起作用。

或者我怎样才能让下划线变强 2px?

http://jsfiddle.net/qJE2w/1/

4

6 回答 6

19

我想到的一个快速解决方案是在伪元素上应用边框:

.border{
    position: relative;
}

.border:hover::after{
    content:'';
    position:absolute;
    width: 100%;
    height: 0;    
    left:0;
    bottom: 4px;                    /* <- distance */
    border-bottom: 2px solid #000;  
}

示例

于 2013-02-06T15:51:57.217 回答
7

您可以使用 line-height 来减少距离。

.underline {
  display: inline-block;
  line-height: 0.9; // the distance
  border-bottom: 1px solid;
}

这种方法的缺点——因为我们使用块显示它只适用于单行文本。

于 2015-01-15T08:27:24.473 回答
3

您可以使用backgroundwithlinear-gradient来生成边框,并且可以将其放置在任何地方。

例如:

background-image: linear-gradient(currentColor, currentColor);
background-position: 0 95%; /* determines how far from bottom */
background-repeat: no-repeat;
background-size: 100% 5px; /* second value determines height of border */

http://jsfiddle.net/1mg4tkwx/

信用:https ://www.dannyguo.com/blog/animated-multiline-link-underlines-with-css/

于 2020-03-09T18:55:52.463 回答
1

多线解决方案

解释。我正在创建一个具有相同文本和文本样式的兄弟姐妹,并且稍微移到顶部。如果你想保持你的代码干净,你可以在页面加载事件中使用 JS 插入兄弟。

限制。此解决方案不适用于文本段落。

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

于 2020-02-16T12:15:16.833 回答
0

这条线对我有用:

.main-nav ul li {
    padding: 0 10px;
}
.main-nav .main-menu  li a {
    border-right: 2px solid #262626; 
    padding: 7px;
}
于 2020-07-20T09:31:46.327 回答
0

我发现一个很酷的解决方案是使用轮廓应用边框,然后在轮廓偏移属性中使用负值。

.outline-border {
  outline: 2px solid red;
  outline-offset: -2px; 
}
于 2021-09-22T16:09:01.570 回答