首页 > 解决方案 > 如何用 HTML 中的图像填充文本?

问题描述

假设我有这样的图像:

我想<h1>用该图像填充一个标签,看起来像这样:

我想我可以做这样的事情开始......

div {
  width: 100%;
  height: 100%;
  background: url(https://i.stack.imgur.com/n8gtc.jpg) 50% 0 no-repeat;
  background-size: cover;
}

h1 {
  color: white;
  text-shadow: -1px 0 black, 0 1px black, 1px 0 black, 0 -1px black;
}
<div>
  <h1>404</h1>
</div>

我应该有另一个覆盖图像的“绝对”div 白色和透明字体吗?有谁知道如何做到这一点?

标签: htmlcss

解决方案


background-clip可能是一个选择

https://developer.mozilla.org/en-US/docs/Web/CSS/background-clip

background-clip CSS 属性设置元素的背景是否延伸到其边框框、填充框或内容框下方。

div {
  width: 100%;
  height: 100%;
}

h1 {
  color: transparent;
  font-size: 28vmax;
  background-size: cover;
  background: url(https://i.stack.imgur.com/n8gtc.jpg) 50% 0 no-repeat;
  background-clip: text;
}
<div>
  <h1>404</h1>
</div>

mix-blend-mode

https://css-tricks.com/almanac/properties/m/mix-blend-mode/

mix-blend-mode 属性定义元素的内容应如何与其背景混合。这意味着任何图像或文本、边框或标题都将受到此属性的影响。

https://developer.mozilla.org/en-US/docs/Web/CSS/mix-blend-mode

mix-blend-mode CSS 属性设置元素的内容应该如何与元素的父元素的内容和元素的背景混合。

* {
  margin: 0;
}

div {
  width: 100%;
  height: 100vh;
  background: url(https://i.stack.imgur.com/n8gtc.jpg) 50% 0 no-repeat;
  background-size: cover;
}

h1 {
  font-size: 15vmax;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  width: 100%;
  color: black;
  text-shadow: -1px 0 black, 0 1px black, 1px 0 black, 0 -1px black;
  background: white;
  mix-blend-mode: screen;
}
<div>
  <h1>404</h1>
</div>


推荐阅读