Warm tip: This article is reproduced from serverfault.com, please click

css-透明文字切出背景

(css - Transparent text cut out of background)

发布于 2012-12-18 12:24:09

有什么方法可以使用CSS从背景效果中切出一个透明文本,如下图所示?
这将是可悲的输,因为替换文本图像的所有珍贵的SEO。

透明文字切出背景

我首先想到了阴影,但是我什么也搞不清...

图片是网站背景,是绝对定位的<img>标签

Questioner
Love Dager
Viewed
0
5,639 2020-07-15 17:03:57

css3有可能,但并非所有浏览器都支持

带背景剪辑:文本;你可以使用背景作为文本,但必须将其与页面背景对齐

body {
    background: url(http://www.color-hex.com/palettes/26323.png) repeat;
    margin:10px;
}
h1 { 
    background-color:#fff;
    overflow:hidden;
    display:inline-block; 
    padding:10px; 
    font-weight:bold;
    font-family:arial;
    color:transparent;
    font-size:200px;
}
span { 
    background: url(http://www.color-hex.com/palettes/26323.png) -20px -20px repeat;
    -webkit-text-fill-color: transparent;
    -webkit-background-clip: text;
    display:block;
}
<h1><span>ABCDEFGHIKJ</span></h1>

http://jsfiddle.net/JGPuZ/1337/


自动对准

用一些JavaScript,你可以自动对齐背景:

$(document).ready(function(){
  //Position of the header in the webpage
  var position = $("h1").position();
  var padding = 10; //Padding set to the header
  var left = position.left + padding;
  var top = position.top + padding;
  $("h1").find("span").css("background-position","-"+left+"px -"+top+"px"); 
});
body {
    background: url(http://www.color-hex.com/palettes/26323.png) repeat;
    margin:10px;
}
h1 { 
    background-color:#fff;
    overflow:hidden;
    display:inline-block; 
    padding:10px; 
    font-weight:bold;
    font-family:arial;
    color:transparent;
    font-size:200px;
}
span { 
    background: url(http://www.color-hex.com/palettes/26323.png) -20px -20px repeat;
    -webkit-text-fill-color: transparent;
    -webkit-background-clip: text;
    display:block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1><span>ABCDEFGHIKJ</span></h1>

http://jsfiddle.net/JGPuZ/1336/