Use SVG as a CSS pseudo element

2024-02-18
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.

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.

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 or CSS | Stack Overflow