32

I want to display an image in a CSS :before element.

.withimage:before {
  content: url(path/to/image.svg);
  display: block;
  height: 20px;
  width: 20px;
}

The problem is, the height and width are applied to the element, but the SVG doesn't scale down. How do I apply the sizes to the actual element created by before?

Plnkr example: https://plnkr.co/edit/UgryaObojs6PCU579oGY

Jorn
  • 20,612
  • 18
  • 79
  • 126
  • This is apparently because the `content` is being handled as static image, not as dynamic SVG, thus it can't be manipulated as XML via CSS. For whatever reasons, the reverse is true when setting the svg file to be the `background-image`. Check out http://stackoverflow.com/a/24026800/49478 – Anthony Mar 28 '16 at 09:45

5 Answers5

41

You can use svg as background-image:

.withimage:before {
  content: "";
  display:block;
  height:125px;
  width:125px;
  background-size: 125px 125px;
  background-image: url(test.svg);
  background-repeat: no-repeat;
}

Here is example

Also you can try use this one:

.withimage:before {
  content: url("data:image/svg+xml; utf8, <svg.. code here</svg>");
    display:block;
    height:20px;
    width:20px;
}
oboshto
  • 3,478
  • 4
  • 25
  • 24
  • 1
    Your example scales ok in Chrome (to test, set all the 125px's to 225px and see the image grow). However, in Edge and Explorer there's no scaling. – thund Oct 06 '17 at 23:38
6

Scale transform worked for me:

::before {
    content: url(path/to/image.svg); // source image is 24px wide
    transform: scale(0.5);           // will be rendered 12px wide
  }
Martin
  • 5,714
  • 2
  • 21
  • 41
2

Sometimes we don't want to use background images for some reasons. I had the same problem you had, and no matter the width and height of the SVG it would not take effect. The reason for this was that the SVG lacked a viewBox.

I just added viewBox='0 0 16 16' in the of the content and violá!

Tony Gustafsson
  • 828
  • 1
  • 7
  • 18
0

most browsers are not support :after,:before on img tags, but you could create a div with height and width and give it a background

Edit you Plunker

/* Styles go here */
.withimage:before {
  content:"";
  background: url(test.svg);
  background-size: cover;
  display: block;
  width:20px;
  height: 10px;
}
.withimage{
  background: pink;
  height: 100px;
  width: 100px;
}
elreeda
  • 4,525
  • 2
  • 18
  • 45
-1

You could just edit the SVG directly:

<svg width="20px" height="20px"

  • He's using it in before pseudo element, if he was using the svg tag directly your answer could be right but now it's incorrect, i don't downvote it but i recommend you to edit or delete it – Mahdiar Mransouri Mar 31 '23 at 18:42