如何使用CurrentColor为边框设置不透明度?

3

我正在自定义链接。我希望边框颜色取决于颜色。为此,我使用CurrentColor。

如何使border-bottom的不透明度为0.5?

a {
  text-decoration: none;
  color: blue;
  border-bottom: 1px solid CurrentColor;
}
<a href="/">Some link</a>

我有一个解决方案,但我不确定它是否是最好的。

a {
  text-decoration: none;
  color: blue;
  background: linear-gradient(to bottom, CurrentColor, transparent 50%) 0 100% repeat-x;
  background-size: 10px 1px;
}
<a href="/">Some link</a>

这个解决方案不起作用。

a {
  --color: blue;
  
  text-decoration: none;
  color: var(blue);
  border-bottom: 1px solid rgba(var(--color), 0.5);
}
<a href="/">Some link</a>

2个回答

5

使用CSS变量需要像这样做:

a {
  --color: 0,0,255;
  
  text-decoration: none;
  color: rgb(var(--color));
  border-bottom: 1px solid rgba(var(--color), 0.2);
}
<a href="/">Some link</a>

对于渐变解决方案,你可以创建两个渐变。一个底部是使用currentColor,另一个顶部是背景颜色(在这种情况下是白色),并调整顶部的不透明度来控制底部的不透明度:

a {
  text-decoration: none;
  color: blue;
  background-image: 
   linear-gradient(rgba(255,255,255,0.8), rgba(255,255,255,0.8)),
   linear-gradient(CurrentColor, CurrentColor);
  background-position:bottom;
  background-size:100% 1px;
  background-repeat:no-repeat;

}
<a href="/">Some link</a>

您可以使用伪元素和不透明度:

a {
  text-decoration: none;
  color: blue;
  position:relative;
}
a:after {
  content:"";
  position:absolute;
  bottom:0;
  right:0;
  left:0;
  height:1px;
  background:currentColor;
  opacity:0.2;
}
<a href="/">Some link</a>

另一个想法是使用类似于我们在渐变中使用的两层box-shadow:

a {
  text-decoration: none;
  color: blue;
  box-shadow:
    0 1px 0 0 rgba(255,255,255,0.8),
    0 1px 0 0 currentColor;
}
<a href="/">Some link</a>


1
因为您设置了--color: blue,但它不是rgb颜色,您需要设置rgb颜色。RGBA中的a代表不透明度。

a {
  --color: 1,1,1;
  
  text-decoration: none;
  color: var(--color);
  border-bottom: 1px solid rgba(var(--color), 0.2);
}
<a href="/">Some link</a>

您可以在这里将颜色转换为RGB:https://www.rapidtables.com/convert/color/hex-to-rgb.html

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接