Use SVG as a CSS pseudo element

Updated at

2024.2.18

Created at

2020.12.11

You can use not only characters but also SVG as CSS pseudo element such as ::before and ::after.

No need to resize SVG

The easiest way is to specify the URL in content directly. If you use url(), you can specify the relative path.

sample.css
p::before {
  content: url("../assets/example.svg");
}

However, you cannot change the size of SVG in this way.

Specify the size of SVG

You have to specify an SVG file as background-image instead of content when resizing SVG.

For example, if the aspect ratio of SVG is 1:1, the code is:

p::before {
  content: "";
  background-image: url("../assets/example.svg");
  display: inline-block;
  height: 1rem;
  width: 1rem;
  vertical-align: middle;
}

Default color of SVG is black. Use the mask attribute to change the color.

Resize and Specify the color

The color of SVG is specified by background-color.

sample.css
p::before {
  content: "";
  background-color: #00ffff;
  display: inline-block;
  height: 1rem;
  width: 1rem;
  -webkit-mask: url("../assets/example.svg");
  mask: url("../assets/example.svg");
  -webkit-mask-size: cover;
  mask-size: cover;
  vertical-align: middle;
}

Use calc() if the aspect of SVG is not 1:1.

Reference

Change SVG fill color in :before or :after CSS | Stack Overflow

mktia's note

Research & Engineering / Blockchain / Web Dev

© 2017-2025 mktia. All rights reserved.