Home > Mobile >  Problem in Displaying SVG in CSS ::before
Problem in Displaying SVG in CSS ::before

Time:11-08

I use CSS ::before to insert images before links.

I am having problems with showing Github SVG. SVG colors do not show properly.

Note: As normal image, the SVG shows fine but as background it doesn't. I have tried no background color, various background colors, as well as transparent.

SVG: https://upload.wikimedia.org/wikipedia/commons/9/91/Octicons-mark-github.svg

a[href^="https://github.com/"]::before {
  content: '';
  background: #000 url('../image/github.svg') no-repeat center;
  background-size: contain;
  display: inline-block;
  height: 1.1em;
  width: 1.1em;
  margin-right: 0.3em;
  vertical-align: text-bottom;
}

Any ideas?

Update: The reason for the problem

TBH, The above code works as pointed out by @AHaworth

The actual CSS is slightly different and there was the problem.

Actual CSS:

a[href^="https://github.com/"]::before,
/* .... */
a[href^="https://www.mozilla.org/"]::before {
  content: '';
  background: url('../image/dino.svg') no-repeat center;
  background-size: contain;
  display: inline-block;
  height: 1.1em;
  width: 1.1em;
  margin-right: 0.3em;
  vertical-align: text-bottom;
}

a[href^="https://github.com/"]::before {
  background: url('../image/github.svg') no-repeat center;
}

Above does not show the image properly.

However, changing it to the following works fine. It seems background-size: contain; needed to be added.

a[href^="https://github.com/"]::before {
  background: url('../image/github.svg') no-repeat center;
  background-size: contain;
}

CodePudding user response:

It shows the image. the problem is that you use black background. remove the #000

a[href^="https://github.com/"]::before {
  content: '';
  background:  url('https://upload.wikimedia.org/wikipedia/commons/9/91/Octicons-mark-github.svg') no-repeat center;
  background-size: contain;
  display: inline-block;
  height: 1.1em;
  width: 1.1em;
  margin-right: 0.3em;
  vertical-align: text-bottom;
}
<a href="https://github.com/">github</a>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Comments seem to indicate there's some misunderstanding so FWIW I put what I did here.

a[href^="https://github.com/"]::before {
  content: '';
  background: pink url('https://upload.wikimedia.org/wikipedia/commons/9/91/Octicons-mark-github.svg') no-repeat center;
  background-size: contain;
  display: inline-block;
  height: 1.1em;
  width: 1.1em;
  margin-right: 0.3em;
  vertical-align: text-bottom;
}
<a href="https://github.com/">Github</a>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Note, in this version I set the background color to pink just to show that effects other than just white are possible.

  • Related