html - 在移动设备上调整 SVG 的大小

标签 html css svg responsive-design responsiveness

如何调整 SVG Logo 的大小以在移动设备上响应?

这是我的 Fiddle我的代码如下:

body {
    background:black;
}

@media screen and (max-width: 500px) {
    svg {
        width:50%;
    }
}
<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<svg version="1.1" preserveAspectRatio="xMinYMin meet" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:sketch="http://www.bohemiancoding.com/sketch/ns">
  <title>Logo</title>
  <desc>Created with Sketch.</desc>
  <defs></defs>
  <g id="Your-Score" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd" sketch:type="MSPage">
    <g id="Desktop-Your-Score" sketch:type="MSLayerGroup" transform="translate(-23.000000, -24.000000)" font-weight="normal" font-family="Gill Sans" letter-spacing="1.16666663" font-size="28" sketch:alignment="middle" fill="#FFFFFF">
      <g id="Header" sketch:type="MSTextLayer">
        <g id="Primary-Nav-[home]-Copy">
          <g id="Logo" transform="translate(23.000000, 18.000000)">
            <text id="TOMORROW’S">
              <tspan x="0.0328778028" y="27">TOMORROW’S</tspan>
              <tspan x="36.2975262" y="58">SCORE</tspan>
            </text>
          </g>
        </g>
      </g>
    </g>
  </g>
</svg>

最佳答案

为了通过 img 元素进行缩放,SVG 图像需要在其中设置其宽度、高度和 viewBox 属性。这是它的样子:

<svg xmlns="http://www.w3.org/2000/svg"
        xmlns:xlink="http://www.w3.org/1999/xlink"
        width="70px" height="70px" viewBox="0 0 70 70">
    <circle cx="40" cy="40" r="24" style="stroke:#006600; fill:#00cc00"/>
</svg>

当设置宽度、高度和 viewBox 属性时,您告诉浏览器要绘制虚拟 Canvas 的哪一部分。 View 框告诉虚拟 Canvas 的左上角和右下角。因此,如果图像被缩放到比该尺寸更大的尺寸,则整个图像都会被放大,而不是仅仅使虚拟 Canvas 变大(导致图像中 SVG 形状旁边出现空白)。

有关 SVG 相关的 viewBox 属性的更多说明。

始终通过 CSS 属性设置图像宽度

不要使用 img 元素的 width 和 height 属性。它不会产生预期的效果。浏览器对待这些属性的方式与相应的 CSS 属性不同。

关于html - 在移动设备上调整 SVG 的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33797776/

相关文章:

html - 如何删除两个表之间的空白?

html - 使用纯 CSS 的增量 CSS 持续时间

html - css 动画空白 : nowrap;

SVG的PHP CSS控件

javascript - 使用 SVG 的圆环图

Javascript 错误 : function not executed, 也不确定图像数组是否已成功添加

html - 在图像上滑动文本 : How to Keep Footer Below All Elements

html - 删除表单中的单选按钮

css - 当包含主题最小 css 时,Bootstrap 3 覆盖导航栏颜色不起作用

javascript - SVG 文本路径动画 : treat path as circle?