Is there a way to use use text as the background with CSS?
I would like to use dynamic text as background of certain elements in my tag. Because of this, I can use images (dynamic text). How do I do it with just CSS or JavaScript?
Solution 1:
SVG text background image
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>
Here is an indented version of the CSS so you can understand better. Note that this does not work, you need to use the single liner SVG from the snippet above instead:
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>");
}
Not sure how portable this is (works on Firefox 31 and Chrome 36), and it is technically an image... but the source is inline and plain text, and it scales infinitely.
@senectus found that it works better on IE if you base64 encode it: https://stackoverflow.com/a/25593531/895245
Solution 2:
You can have an absolutely positioned element inside of your relative positioned element:
#container {
position: relative;
}
#background {
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
z-index: -1;
overflow: hidden;
}
<div id="container">
<div id="background">
Text to have as background
</div>
Normal contents
</div>
Here's an example of it.
Solution 3:
It may be possible (but very hackish) with only CSS using the :before or :after pseudo elements:
.bgtext {
position: relative;
}
.bgtext:after {
content: "Background text";
position: absolute;
top: 0;
left: 0;
z-index: -1;
}
<div class="bgtext">
Foreground text
</div>
This seems to work, but you'll probably need to tweak it a little. Also note it won't work in IE6 because it doesn't support :after
.
Solution 4:
Ciro's solution about an SVG Data URI background containing the text is very clever.
However, it won't work in IE if you just add the plain SVG source to the data URI.
In order to get around this and make it work in IE9 and up, encode the SVG to base64. This is a great tool.
So this:
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>');
Becomes this:
background:url('data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPjx0ZXh0IHg9IjUlIiB5PSI1JSIgZm9udC1zaXplPSIzMCIgZmlsbD0icmVkIj5JIGxvdmUgU1ZHITwvdGV4dD48L3N2Zz4=');
Tested and it works in IE9-10-11, WebKit (Chrome 37, Opera 23) and Gecko (Firefox 31).
http://jsfiddle.net/qapp5dLn/