有没有办法将使用文字作为CSS的背景?

我想使用dynamic文本作为我的标记中的某些元素的背景。 因此,我可以使用图像(dynamic文本)。 我如何用CSS或JavaScript做到这一点?

你可以在你的相对定位元素中有一个绝对定位的元素:

<div id="container"> <div id="background"> Text to have as background </div> Normal contents </div> 

然后CSS:

 #container { position: relative; } #background { position: absolute; top: 0; left: 0; bottom: 0; right: 0; z-index: -1; overflow: hidden; } 

这是一个例子 。

怎么样一个SVG文字背景图片

 body { background-image:url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' version='1.1' height='50px' width='120px'><text x='0' y='15' fill='red' font-size='20'>I love SVG!</text></svg>"); } 
 <p>I hate SVG!</p><p>I hate SVG!</p><p>I hate SVG!</p><p>I hate SVG!</p> <p>I hate SVG!</p><p>I hate SVG!</p><p>I hate SVG!</p><p>I hate SVG!</p> 

使用:before或之后的伪元素可能(但非常hackish)只有CSS:

 <style type="text/css"> .bgtext { position: relative; } .bgtext:after { content: "Background text"; position: absolute; top: 0; left: 0; z-index: -1; } </style> <div class="bgtext"> Foreground text </div> 

这似乎工作,但你可能需要稍微调整一下。 另外请注意,它不会在IE6中工作,因为它不支持:after

Ciro关于包含文本的SVG数据URI背景的解决scheme非常聪明。

但是,如果只是将简单的SVG源添加到数据URI,则在IE中不起作用。

为了解决这个问题,并使其在IE9和以上工作,编码SVG到base64。 这是一个伟大的工具。

所以这:

 background:url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg"><text x="5%" y="5%" font-size="30" fill="red">I love SVG!</text></svg>'); 

变成这样:

 background:url('data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPjx0ZXh0IHg9IjUlIiB5PSI1JSIgZm9udC1zaXplPSIzMCIgZmlsbD0icmVkIj5JIGxvdmUgU1ZHITwvdGV4dD48L3N2Zz4='); 

经testing,它可以在IE9-10-11,WebKit(Chrome 37,Opera 23)和Gecko(Firefox 31)上运行。

http://jsfiddle.net/qapp5dLn/

您可以使包含bg文本的元素具有较低的堆叠顺序(z-index,position),甚至可以设置不透明度。 所以你需要在上面的元素需要更高的堆栈顺序(z-index:5; position:relative;对于ex),并且后面的元素需要更低的值(默认值或只是一个较低的z-index值,如3和position:relative ;)。

@Ciro

你可以用斜线"\"来打破内联svg代码

在Chrome 54和Firefox 50中使用以下代码进行testing

 body { background: transparent; background-attachment:fixed; background-image: url( "data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' version='1.1' width='170px' height='50px'> \ <rect x='0' y='0' width='170' height='50' style='stroke:white; fill:gray; stroke-opacity: 0.3; stroke-width: 3px; fill-opacity: 0.7; stroke-dasharray: 10 5; stroke-linecap=round; '/> \ <text x='85' y='30' style='fill:lightBlue; text-anchor: middle' font-size='16' transform='rotate(10,85,25)'>I love SVG!</text></svg>"); } 

我甚至testing过这个,

 background-image: url("\ data:image/svg+xml;utf8, \ <svg xmlns='http://www.w3.org/2000/svg' version='1.1' width='170px' height='50px'> \ <rect x='0' y='0' width='170' height='50'\ style='stroke:white; stroke-width: 3px; stroke-opacity: 0.3; \ stroke-dasharray: 10 5; stroke-linecap=round; \ fill:gray; fill-opacity: 0.7; '/> \ <text x='85' y='30' \ style='fill:lightBlue; text-anchor: middle' font-size='16' \ transform='rotate(10,85,25)'> \ I love SVG! \ </text> \ </svg>\ "); 

它可以工作(至less在Chrome 54和Firefox 50 ==>在NWjs&Electron中使用保证)