【问题标题】:SVG doesn't respect background-size 100% 100%SVG 不尊重背景大小 100% 100%
【发布时间】:2018-10-18 16:51:17
【问题描述】:

我有this SVG image,我想覆盖一个完整的容器,保持其独特的边缘。 background-size: 100% 100%; 似乎是完美的选择,虽然它适用于常规图像,但在这种情况下不起作用。为什么?

(jpeg 取自 James' 答案)

html, body {
  background-color: #ddd;
}
.container {
  margin: 20px; padding: 20px; border: 1px solid #000;

  background-repeat: no-repeat;
  background-size: 100% 100%;
}
.container.svg {
  background-image: url(https://svgshare.com/i/RWM.svg);
}
.container.img {
  background-image: url(https://images.pexels.com/photos/370799/pexels-photo-370799.jpeg?auto=compress&cs=tinysrgb&h=350);
}
<div class="container svg">
  some<br>content<br>makes<br>this<br>large
</div>
<div class="container img">
  some<br>content<br>makes<br>this<br>large
</div>

【问题讨论】:

  • 这很混乱,你说的填充整个区域而不是覆盖它是什么意思?
  • @ZohirSalakCeNa cover 按比例缩放图像,但我的图像有非常特殊的边缘,我想让它们都可见

标签: css image svg background-image


【解决方案1】:

好的,我是在阅读了其他几个主题后才弄清楚的——包括那些有效的主题。

罪魁祸首是viewBox 定义中的&lt;svg&gt;。当我删除它时,图像会按比例缩放。对于 safari,我需要添加 preserveAspectRatio="none"

之前:

<svg width="392px" height="499px" viewBox="0 0 392 499" ...

之后:

<svg width="392px" height="499px" preserveAspectRatio="none" ...

html, body {
  background-color: #ddd;
}
.container {
  margin: 20px; padding: 20px; border: 1px solid #000;

  background-repeat: no-repeat;
  background-size: 100% 100%;
}
.container.svg {
  background-image: url(https://svgshare.com/i/RWM.svg);
}
.container.img {
  background-image: url(https://svgshare.com/i/RWv.svg);
}
<div class="container svg">
  some<br>content<br>makes<br>this<br>large
</div>
<div class="container img">
  some<br>content<br>makes<br>this<br>large
</div>

【讨论】:

    【解决方案2】:

    background-size: 100% 100%; 应该做你的伎俩。请检查您的代码是否没有错误。

    这是一个小提琴:https://jsfiddle.net/7pn3cvh3/

    【讨论】:

    • doesn't work with my SVG,我会改写问题
    • 在这种情况下,您可以通过三种方式执行此操作: 1. 将其导出为高分辨率 PNG ant,它仍然具有良好的质量,并且可以使用 background-size: 100% 100%; 2. 将 SVG 分成两个 SVG(垂直和水平),并将它们用作 CSS 中的 :before 和 :after 元素,背景位置:包含; 3. 使用jQuery测量div的高度并将尺寸输出到DOM为style="background-size: ***px ***px";
    • 我喜欢 SVG 的小尺寸,所以高分辨率 PNG 并不是一个真正的选择。无论如何,从代码中删除 viewBox 就可以了
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-18
    • 2014-09-10
    • 2013-03-24
    • 1970-01-01
    • 2021-01-30
    • 2013-12-21
    相关资源
    最近更新 更多