HTML injection via CSS

I need to basically install content

something with HTML from CSS. I am currently doing the following:

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


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

<img src="hello.png"/>


How can I insert arbitrary HTML using CSS?


source to share

5 answers

HTML stores data and is a model CSS stores styles and this kind of JS stores interactions and is a controller

If you are trying to add data to a page, it must be done via HTML. If you're just trying to add an image as a style, use the background-image

. You don't need to enter an element <img>

on the page to do this.

Never do this

As far as being able to embed HTML into a page via CSS, it is not possible, but it is possible to add JavaScript to a page using CSS , which can then add HTML to the page.

I cannot stress how wrong this approach would be.



Unless there is some weird hack that I am not aware of, this cannot be done with pure CSS.

The property content

can only insert text; if you try to put in HTML it will be escaped.

However, you can do something like this with pure CSS:

enter image description here

This is the CSS that can accomplish this effect:

.myClass:before {
  display: inline-block;
  width: 32px;
  height: 32px;
  content: "";
  background-image: url("img.gif");


This can be seen on this jsFiddle page .



In this particular case, you can use a pseudo class (for example ::before

) background-image

, display:block

and a fixed width and height to show the image.

Also, make sure to :

add a colon between content

and its value.

A relatively new concept on the horizon is element()

background meaning . This will render the HTML as if it were an image: See Also -moz-element




You can not. It's not for what. CSS is for the presentation layer whereas HTML is for the data layer.

Actually you can, but only for characters, not HTML. You can use the property content

. With some CSS selectors like this :before

, you can do nice things like add your own character as a bullet for your list. But not much more.



It can be done. For example with Firefox


  -moz-binding: url(stackexchange.xml#hlinks);



<bindings xmlns=""
  <binding id="hlinks">
      <html:a href="/privileges">privileges</html:a>
      <html:span class="lsep"> | </html:span>
      <html:a href="/users/logout">log out</html:a>


ref 1

ref 2



All Articles