如何在文本上应用CSS渐变,从透明到不透明的颜色

47

干杯!

我是CSS/HTML的新手,但我想在文本上应用渐变,就像下面的图片一样。我该如何用CSS实现呢?


输入图像描述


3
你尝试了什么?我认为你的意思是不透明度,而不是阴影。 - Vucko
3个回答

86

相关的CSS位于我使用的<article>包装器的伪元素:after上。

article {
  position: relative;
}

article:after {
  position: absolute;
  bottom: 0;  
  height: 100%;
  width: 100%;
  content: "";
  background: linear-gradient(to top,
     rgba(255,255,255, 1) 20%, 
     rgba(255,255,255, 0) 80%
  );
  pointer-events: none; /* so the text is still selectable */
}
  <article>
      <p>
         Had you stepped on board the Pequod at a certain juncture 
         of this post-mortemizing of the whale; and had you strolled
         forward nigh the windlass, pretty sure am I that you would
         have scanned with no small curiosity a very strange, enigmatical 
         object, which you would have seen there, lying along lengthwise 
         in the lee scuppers. Had you stepped on board the Pequod at a certain 
         juncture of this post-mortemizing of the whale; and had you strolled
         forward nigh the windlass, pretty sure am I that you would
         have scanned with no small curiosity a very strange, enigmatical 
         object, which you would have seen there, lying along lengthwise 
         in the lee scuppers.
      </p>
  </article> 


你应该将其固定到底部高度,这样80%的文本将保持可选择状态。 - korywka
如果您需要淡出位于具有不透明度(即半透明)的图层上方的文本,则此方法将无法正常工作。 - thdoan

16

这是一个很棒的小技巧。根据CanIUse的数据,在英国有95%的用户可以使用它,在全球范围内则有91%。不错哦。 - Chuck Le Butt
这在Chrome、Safari和Firefox中有效。但在IE11中无效,如果您仍需要支持,请注意以下有趣的一点是我发现定义它们的顺序实际上很重要。将背景放在其他元素之上。 - jxn

5
您也可以使用mask-image属性来实现这一点,不过您可能需要添加-webkit-前缀。

article {
  -webkit-mask-image: linear-gradient(0deg, transparent 16px, red 66px);
  /* 0deg = down, 90deg = left, 180deg = top, 270deg = right */
}
  <article>
      <p>
         Had you stepped on board the Pequod at a certain juncture 
         of this post-mortemizing of the whale; and had you strolled
         forward nigh the windlass, pretty sure am I that you would
         have scanned with no small curiosity a very strange, enigmatical 
         object, which you would have seen there, lying along lengthwise 
         in the lee scuppers. Had you stepped on board the Pequod at a certain 
         juncture of this post-mortemizing of the whale; and had you strolled
         forward nigh the windlass, pretty sure am I that you would
         have scanned with no small curiosity a very strange, enigmatical 
         object, which you would have seen there, lying along lengthwise 
         in the lee scuppers.
      </p>
  </article> 


1
这绝对是最干净的解决方案! - Jonathan

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