首页 > 解决方案 > CSS background-clip:来自父元素背景的文本

问题描述

我试图让background-clip: text一个子 div 从父 div 获取它的背景。基本上它应该看起来像文本被剪掉了。

当背景在同一个元素上时很容易做到,但我似乎无法弄清楚背景何时在不同的 div 上。

.background {
    width: 100%;
    height: 700px;
    background: url('http://bgfons.com/uploads/gold/gold_texture464.jpg');
    background-size: cover;
    display: flex;
    justify-content: center;
    align-items: center;
}

.background > div {
    flex: 1;
    font-size: 5em;
    font-weight: bold;
    text-align: center;
}

.foreground1 {
    background-clip: text;
    -webkit-background-clip: text;
    color: transparent;
}
<div class="background">
    <div class="foreground1">This is some text</div>
    <div class="foreground2">This is some text</div>
</div>

我在 Plunkr 中有以下内容(文本应该从背景图像中获取颜色):

https://next.plnkr.co/edit/4lGVXnfvex9Q6mmY?open=lib%2Fscript.js

这可能吗?如果可以,怎么做?任何帮助表示赞赏。

标签: css

解决方案


您必须应用background-clip到要剪辑的背景:

.background {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  background: url('http://bgfons.com/uploads/gold/gold_texture464.jpg');
  background-size: cover;
  background-clip: text;
  -webkit-background-clip: text;
}

.background>div {
  flex: 1;
  font-size: 3em;
  font-weight: bold;
  text-align: center;
}

.foreground1 {
  color: transparent;
}
<div class="background">
  <div class="foreground1">This is some text</div>
  <div class="foreground2">This is some text</div>
</div>


推荐阅读