【问题标题】:Problem in Displaying SVG in CSS ::before在 CSS ::before 中显示 SVG 的问题
【发布时间】:2021-12-20 19:50:51
【问题描述】:

我使用 CSS ::before 在链接前插入图片。

我在显示 Github SVG 时遇到问题。 SVG 颜色无法正确显示。

注意:作为普通图像,SVG 显示正常,但 background 却没有。 我试过没有背景色,各种背景色,还有透明的。

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;
}

有什么想法吗?

更新:问题的原因

TBH,上面的代码如@AHaworth所指出的那样工作

实际的 CSS 略有不同,存在问题。

实际的 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;
}

上面没有正确显示图像。

但是,将其更改为以下内容可以正常工作。似乎需要添加background-size: contain;

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

【问题讨论】:

  • github 图像没有问题 - 它只是在黑色背景下显示不佳。您能否解释一下“SVG 颜色无法正确显示”是什么意思,因为徽标在透明背景上似乎只是暗色。
  • @AHaworth 确实是这样,为什么我对这个特定的问题有疑问。我尝试在 SVG 中设置填充,更改背景颜色但仍无法正确显示图像。我该怎么办?
  • 你能不能只给它一个白色或其他适合我的浅色背景色。
  • 你设置了什么?是否有理由想要透明?我刚刚设置了 background-color: white 并看到了很好的标志。这是一种 CSS 设置,而不是 SVG 设置。
  • @AHaworth 感谢您的帮助。我发现了问题并更新了帖子,以防它可能对某人有用。

标签: css svg


【解决方案1】:

它显示图像。问题是您使用黑色背景。删除#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>

【讨论】:

  • 您使用的是.png 版本。你能用 .svg 版本来展示它吗?
  • 我觉得没关系,发个图片链接
  • 帖子已更新。
  • @erosman 工作得很好。问题是您使用了具有透明背景和蒙版黑色(#000)的图像,这使得图像看起来像黑色
【解决方案2】:

评论似乎表明存在一些误解,所以 FWIW 我把我所做的放在这里。

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>

注意,在这个版本中,我将背景颜色设置为粉红色只是为了表明除了白色之外的其他效果也是可能的。

【讨论】:

    猜你喜欢
    • 2015-01-09
    • 2011-09-28
    • 2017-10-18
    • 2011-04-07
    • 2021-11-07
    • 2012-05-15
    • 2023-04-01
    • 2011-07-13
    相关资源
    最近更新 更多