Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use SVG in pseudo element content or background image in Vue template file

Tags:

css

vue.js

I don't know how I can use a SVG file as a pseudo content element in Vue template files.

In the scoped CSS of my Vue template file (Select.vue) I have:

.wrap {
  &:after {
    content: url("../../assets/icons/caret-down-solid.svg");
    position: absolute;
    right: 0;
    width: 50px;
    height: 50px;
  }
}

the path is relative of the components location. But it does not simply show up.

Things I have tried and noticed:

  • I have tried without the " " around the URL too.
  • I have tried using a background-image and content: " " instead, didn't work either.
  • It works with an absolute URL (for example a testfile on the web)
  • It does resolve the local URL in my example because when I do ../../../asserts/icons/caret-down-solid.svg to take a wrong path it will fail compiling.

So it looks like the file gets resolved, the syntax is correct, but it does not show up for whatever reason.

Edit: When inspecting the pseudo element while using background-image I see:

background-image: url([object Module]);

like image 728
supersize Avatar asked Nov 19 '25 14:11

supersize


1 Answers

In case someone comes across this question I managed to solve this. Problem was that the vue-svg-loader I was using was importing the .svg file as a module. So I had to use an svg-url-loader for importing svgs into styles.

In my vue.config.js under the chainWebpack option I was adding:

config.module.rule("svg")
  .oneOf("inline")
    .resourceQuery(/inline/)
    .use("svg-url-loader")
      .loader("svg-url-loader")
      .end()
    .end()
  .oneOf("external")
    .use("vue-svg-loader")
      .loader("vue-svg-loader");

what this does is when you append a ?inline to your svg it will treat it with a different loader (svg-url-loader in this case)

So in the CSS you do:

.wrap {
  &:after {
    content: url("../../assets/icons/caret-down-solid.svg?inline");
    position: absolute;
    right: 0;
    width: 50px;
    height: 50px;
  }
}

and it will import the SVG properly inline.

like image 146
supersize Avatar answered Nov 21 '25 04:11

supersize