代码之家  ›  专栏  ›  技术社区  ›  Neekoy

CSS背景剪辑:来自父元素背景的文本

css
  •  1
  • Neekoy  · 技术社区  · 6 年前

    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

    这可能吗?如果可能,如何实现?感谢您的帮助。

    1 回复  |  直到 6 年前
        1
  •  3
  •   Kosh    6 年前

    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>