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?
CSS can insert text content before or after an element. To specify this, make a rule and add ::before or ::after to the selector. In the declaration, specify the content property with the text content as its value.
Changing Text Background Color in CSS. To change the background color of the inline text, go to the <head> section. Simply add the appropriate CSS selector and define the color and background-color property with the values you want.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With