Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Injecting HTML via CSS

Tags:

html

css

I need to basically set the content of something with HTML from CSS. I'm currently doing the following:

.myclass {
    content "<img src=\"hello.png\"/>";
}

However, instead of the image, I see the literal text:

<img src="hello.png"/>

How can I inject arbitrary HTML using CSS?

like image 925
Naftuli Kay Avatar asked Mar 16 '12 15:03

Naftuli Kay


People also ask

How do I inject CSS to HTML?

CSS can be added to HTML documents in 3 ways: Inline - by using the style attribute inside HTML elements. Internal - by using a <style> element in the <head> section. External - by using a <link> element to link to an external CSS file.

Can I put HTML code in CSS?

No, you cannot insert HTML code from CSS.


1 Answers

HTML stores the data, and is the Model
CSS stores the styles, and is the View
JS stores the interactions, and is the Controller

If you're trying to add data to the page, it should be done via HTML. If you're simply trying to add an image as a style, use the background-image property. You don't need to inject an <img> element in the page to do that.

Don't ever do this, ever

As far as being able to inject HTML into the page via CSS, it's not directly possible, however it's possible to add JavaScript into the page using CSS, which can then add HTML to the page.

I can't emphasize enough how wrong that approach would be.

like image 178
zzzzBov Avatar answered Nov 15 '22 21:11

zzzzBov