html - CSS中彩色背景上的透明文本

标签 html css

是否可以使用 CSS 在带有彩色背景和透明字符的 div/span/etc 中显示一些文本?我附上了一张图片来简单地展示我想要做什么。

我的 HTML 代码:

<div id="container">
    <div id="textbox">this text is transparent</div>
</div>

我的 CSS 代码:

#container {
    display: block;
    width: 400px;
    height: 200px;
    background-image: url('...path/to/myimage.jpg');
}
#textbox {
    background: #000;
    color: transparent; /* ??? */
}

transparent text on image via CSS

最佳答案

您可以使用 SVG,它需要一些额外的调整:svg 的宽度以便查看所有文本,设置与背景相同的背景图案。

SVG 文本还没有换行(svg 2.0 应该)。

唯一的好处是Firefox在background-clip:text时支持;没有。

DEMO

HTML + SVG 内联内容:

</div>
  <svg height="5em" width="32em">
    <defs>
      <pattern id="textpattern" patternUnits="userSpaceOnUse" width="1000" height="1000" >
        <image xlink:href="http://lorempixel.com/600/300/nature/9" width="600" height="300"  x="-3em" y="-3em"/>
      </pattern>
    </defs>
    <text  y="1.2em" x="0.5em" >​this text is transparent</text>
  </svg>
</div>

将 CSS 关联到演示:

text {
  font-size:3em;
  fill:url(#textpattern) ;
}
svg {
  background:rgba(0,0,0,0.9);
  margin:2em 0 0 2em;
}
#container {
  padding:1em;
  background:url(http://lorempixel.com/600/300/nature/9) no-repeat;
}

关于html - CSS中彩色背景上的透明文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23794947/

相关文章:

javascript - 为什么 JavaScript 代码无法在 codepen.io 中运行

c# - SFTP URL 的正则表达式

html - 仅从左侧删除阴影

html - 是否有现代的网络安全字体列表?

css - 如何在外部 CSS 中取消特定的一个元素?

javascript - 当只用 JS 悬停时,如何在我的网站上显示一个元素?

javascript - 没有固定高度的页脚位置

html - 为什么在应用填充时 <p> 结束在另一个 <div> 中,而不是在其中扩展 div?

javascript - 使用带有新 id 的 javascript 克隆 html 中的 div

javascript - 通过 webview 动态调整应用程序窗口(边界)的大小