html - 无法将 SVG 符号 Sprite 用作背景

标签 html css svg sprite

我有这个页面布局和CSS http://codepen.io/anon/pen/QjRBrO?editors=110

Sprite 中的 SVG 图标,插入 use 标签效果很好:

    <svg class="social__item">
      <use xlink:href="images/sprite.svg#vk"></use>
    </svg>

但是当我尝试将 Sprite 公园设置为背景时它不起作用:

    .social__item_vk {
      background: #ccc url(images/sprite.svg#vk) no-repeat;
    }

这是我的 svg Sprite :http://controlsk.ru/test/images/sprite.svg

最佳答案

svg 中至少有两种已知的使用 Sprite 的模式文件:<view><symbol> 。请参阅下面的用法。

  1. <view>模式,非常适合在 css 中使用(背景、滤镜等)。
    svg 文件结构示例:

     <view id="icon--sidebar" viewBox="0 0 50 50" />
     <svg viewBox="-10.67 -10.67 533.33 533.33" width="50" height="50" xmlns="http://www.w3.org/2000/svg">
         <path d="M512 0v512H0V0h512zM40.421 471.579h431.158V40.421H40.421v431.158zM67.368 67.368h161.685v377.264H67.368V67.368zm377.264 161.685H327.868l49.395-67.368h-53.895L256 256l67.368 94.315h53.895l-49.395-67.368h116.764v-53.894z" />
     </svg>
    
     <view id="icon--text" viewBox="50 0 34 34" />
     <svg viewBox="-1 -1 34 34" width="34" height="34" x="50" xmlns="http://www.w3.org/2000/svg">
         <path d="M24 14V6s0-4-4-4h-8C8 2 8 6 8 6v8H0v2h8v14h4v-8h8v8h4V16h8v-2h-8zm-4 4h-8v-2h8v2zm0-4h-8V6h8v8z" />
     </svg>
    

css 用法,其中 .svg 旁边的字符串文件扩展名和 "#"是一个 ID,与 Sprite 中所需的图标相关联:

.item {
    background: #ccc url(images/sprite.svg#icon--sidebar) no-repeat;
}
  • <symbol>模式,可以在 HTML 标记中使用此模式从内部调用必要的图标。
    svg 文件结构示例:

     <symbol viewBox="-10.67 -10.67 533.33 533.33" id="icon--sidebar" xmlns="http://www.w3.org/2000/svg">
         <path d="M512 0v512H0V0h512zM40.421 471.579h431.158V40.421H40.421v431.158zM67.368 67.368h161.685v377.264H67.368V67.368zm377.264 161.685H327.868l49.395-67.368h-53.895L256 256l67.368 94.315h53.895l-49.395-67.368h116.764v-53.894z" />
     </symbol>
    
     <symbol viewBox="-1 -1 34 34" id="icon--text" xmlns="http://www.w3.org/2000/svg">
         <path d="M24 14V6s0-4-4-4h-8C8 2 8 6 8 6v8H0v2h8v14h4v-8h8v8h4V16h8v-2h-8zm-4 4h-8v-2h8v2zm0-4h-8V6h8v8z"/>
     </symbol>
    
  • html 用法:

    <svg>
       <use xlink:href="images/sprite.svg#icon--sidebar"></use>
    </svg>
    

    关于html - 无法将 SVG 符号 Sprite 用作背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33904147/

    相关文章:

    java - 从 JSP 生成 HTML

    css - 选择元素下方具有某些类的后代

    html - 响应内容问题,内容从容器中出来

    javascript - SVG Circle 元素在比例变换时跳跃

    css svg 和矢量效果 ="non-scaling-stroke"浏览器兼容性

    html - 如何更改 Angular ui-grid 中拖动工具(或)调整大小工具的颜色?

    html - CSS - 更改宽度 :after elements using content?

    javascript - 使行扩展元素即 extjs 网格和图表可在窗口调整大小时调整大小

    css - 如何使用 SVG 形状进行图像裁剪?

    html - 使用 css3 创建 Logo