带有SVGCSS:真实世界的用法

SVG is a lightweight vector image format that’s used to display a variety of graphics on the Web and other environments with support for interactivity and animation. In this article, we’ll explore the various ways to use CSS with SVG, and ways to include SVGs in a web page and manipulate them.

SVG是一种轻量级的矢量图像格式,用于在Web和其他环境上显示各种图形,并支持交互性和动画。 在本文中,我们将探讨将CSS与SVG结合使用的各种方法,以及将SVG包含在网页中并对其进行操作的方法。

The Scalable Vector Graphic (SVG) format has been an open standard since 1999, but browser usage became practical in 2011 following the release of Internet Explorer 9. Today, SVG is well supported across all browsers, although more advanced features can vary.

自1999年以来,可伸缩矢量图形(SVG)格式一直是一种开放标准,但是随着Internet Explorer 9的发布,浏览器的使用在2011年变得实用。如今,尽管更多高级功能可能有所不同,但所有浏览器都很好地支持SVG

SVG的好处 (SVG Benefits)

Bitmap images such as PNGs, JPGs and GIFs define the color of individual pixels. An 100×100 PNG image requires 10,000 pixels. Each pixel requires four bytes for red, green, blue and transparency so the resulting file is 40,000 bytes (plus a little more for meta data). Compression is applied to reduce the file size; PNG and GIF use ZIP-like lossless compression while JPG is lossy and removes less noticeable details.

位图图像(例如PNG,JPG和GIF)定义了各个像素的颜色。 100×100 PNG图像需要10,000像素。 每个像素需要四个字节来表示红色,绿色,蓝色和透明性,因此生成的文件为40,000个字节(再加上一些元数据)。 应用压缩以减小文件大小; PNG和GIF使用类似ZIP的无损压缩,而JPG有损,并删除不太明显的细节。

Bitmaps are ideal for photographs and more complex images, but definition is lost as the images are enlarged.

位图是照片和更复杂图像的理想选择,但是随着图像放大,清晰度会丢失。

SVGs are vector images defined in XML. Points, lines, curves, paths, ellipses, rectangles, text, etc. are drawn on an SVG canvas. For example:

SVG是用XML定义的矢量图像。 点,线,曲线,路径,椭圆,矩形,文本等在SVG画布上绘制 。 例如:

<svg xmlns="https://www.w3.org/2000/svg" viewBox="0 0 800 600">
  <circle cx="400" cy="300" r="250" stroke-width="20" stroke="#f00" fill="#ff0" />
</svg>

The viewBox defines a co-ordinate space. In this example, an 800×600 area starting at position 0,0 has a yellow circle with a red border drawn in the center:

viewBox定义了一个坐标空间。 在此示例中,从位置0,0开始的800×600区域的中心是黄色圆圈,并带有红色边框:

SVG circle

The benefits of vectors over bitmaps:

向量优于位图的优点:

  • the SVG above uses less than 150 bytes, which is considerably smaller than an equivalent PNG or JPG

    上面的SVG使用的字节数少于150个,比同等的PNG或JPG小得多
  • SVG backgrounds are transparent by default

    SVG背景默认为透明
  • the image can scale to any size without losing quality

    图像可以缩放到任意大小而不会降低质量
  • SVG code/elements can be easily generated and manipulated on the server or browser

    SVG代码/元素可以在服务器或浏览器上轻松生成和操纵
  • in terms of accessibility and SEO, text and drawing elements are machine and human-readable.

    就可访问性和SEO而言,文本和绘图元素是机器和人类可读的。

SVG is ideal for logos, charts, icons, and simpler diagrams. Only photographs are generally impractical, although SVGs have been used for lazy-loading placeholders.

SVG非常适合徽标,图表,图标和更简单的图表。 尽管SVG已用于延迟加载占位符 ,但通常仅照片是不切实际的。

SVG工具 (SVG Tools)

It’s useful to understand the basics of SVG drawing, but you’ll soon want to create more complex shapes with an editor that can generate the code. Options include:

理解SVG绘图基础很有用,但是您很快就会希望使用可以生成代码的编辑器来创建更复杂的形状。 选项包括:

Each has different strengths, and you’ll get differing results for seemingly identical images. In general, more complex images require more complex software.

每个都有不同的优势,对于看似相同的图像,您将获得不同的结果。 通常,更复杂的图像需要更复杂的软件。

The resulting code can usually be simplified and minimized further using SVGO (plugins are available for most build tools) or Jake Archibold’s SVGOMG interactive tool.

通常,可以使用SVGO ( 大多数构建工具都提供插件)来简化和最小化结果代码,或者使用Jake Archibold的SVGOMG交互式工具

SVG作为静态图像 (SVGs as Static Images)

When used within an HTML <img> tag or CSS background-url, SVGs act identically to bitmaps:

在HTML <img>标签或CSS background-url ,SVG的作用与位图相同:

<!-- HTML image -->
<img src="myimage.svg" alt="a vector graphic" />
/* CSS background */
.myelement {
  background-image: url('mybackground.svg');
}

The browser will disable any scripts, links, and other interactive features embedded into the SVG file. You can manipulate an SVG using CSS in an identical way to other images using transform, filters, etc. The results of using CSS with SVG are often superior to bitmaps, because SVGs can be infinitely scaled.

浏览器将禁用SVG文件中嵌入的所有脚本,链接和其他交互功能。 您可以使用CSS使用SVG来处理SVG,方法与使用transformfilters等其他图像相同。将CSS与SVG一起使用的结果通常优于位图,因为SVG可以无限缩放。

CSS内联SVG背景 (CSS Inlined SVG Backgrounds)

An SVG can be inlined directly in CSS code as a background image. This can be ideal for smaller, reusable icons and avoids additional HTTP requests. For example:

SVG可以直接嵌入CSS代码中作为背景图像。 这对于较小的可重复使用的图标非常理想,并且避免了其他HTTP请求。 例如:

.mysvgbackground {
  background: url('data:image/svg+xml;utf8,<svg xmlns="https://www.w3.org/2000/svg" viewBox="0 0 800 600"><circle cx="400" cy="300" r="50" stroke-width="5" stroke="#f00" fill="#ff0" /></svg>') center center no-repeat;
}

Standard UTF-8 encoding (rather than base64) can be used, so it’s easy to edit the SVG image if necessary.

可以使用标准UTF-8编码(而不是base64),因此如有必要,可以轻松地编辑SVG图像。

带有SVGCSS:响应式SVG图像 (CSS with SVG: Responsive SVG Images)

When creating a responsive website, it’s normally practical to omit <img> width and height attributes and allow an image to size to its maximum width via CSS:

创建响应式网站时,通常可以省略<img> widthheight属性,并允许通过CSS将图片调整为最大宽度:

img {
  display: block;
  max-width: 100%;
}

However, an SVG used as an image has no implicit dimensions. You might discover the max-width is calculated as zero and the image disappears entirely. To fix the problem, ensure a default width and height is defined in the <svg> tag:

但是,用作图像的SVG没有隐式尺寸。 您可能会发现max-width被计算为零,并且图像完全消失了。 要解决此问题,请确保在<svg>标记中定义了默认的widthheight

<svg xmlns="https://www.w3.org/2000/svg" width="400" height="300">

Note: the dimensions should not be added to inlined SVGs, as we’ll discover in the next section …

注意:尺寸不应添加到内联SVG中,因为我们将在下一部分中发现……

HTML内嵌的SVG图片 (HTML-Inlined SVG Images)

SVGs can be placed directly into the HTML. When this is done, they become part of the DOM and can be manipulated with CSS and JavaScript:

SVG可以直接放入HTML中。 完成此操作后,它们将成为DOM的一部分,并且可以使用CSS和JavaScript进行操作:

<p>SVG is inlined directly into the HTML:</p>

<svg id="invader" xmlns="https://www.w3.org/2000/svg" viewBox="35.4 35.4 195.8 141.8">
  <path d="M70.9 35.4v17.8h17.7V35.4H70.9zm17.7 17.8v17.7H70.9v17.7H53.2V53.2H35.4V124h17.8v17.7h17.7v17.7h17.7v-17.7h88.6v17.7h17.7v-17.7h17.7V124h17.7V53.2h-17.7v35.4h-17.7V70.9h-17.7V53.2h-17.8v17.7H106.3V53.2H88.6zm88.6 0h17.7V35.4h-17.7v17.8zm17.7 106.2v17.8h17.7v-17.8h-17.7zm-124 0H53.2v17.8h17.7v-17.8zm17.7-70.8h17.7v17.7H88.6V88.6zm70.8 0h17.8v17.7h-17.8V88.6z"/>
  <path d="M319 35.4v17.8h17.6V35.4H319zm17.6 17.8v17.7H319v17.7h-17.7v17.7h-17.7V159.4h17.7V124h17.7v35.4h17.7v-17.7H425.2v17.7h17.7V124h17.7v35.4h17.7V106.3h-17.7V88.6H443V70.9h-17.7V53.2h-17.7v17.7h-53.2V53.2h-17.7zm88.6 0h17.7V35.4h-17.7v17.8zm0 106.2h-35.5v17.8h35.5v-17.8zm-88.6 0v17.8h35.5v-17.8h-35.5zm0-70.8h17.7v17.7h-17.7V88.6zm70.9 0h17.7v17.7h-17.7V88.6z"/>
</svg>

<p>The SVG is now part of the DOM.</p>

No width or height attributes are defined for the SVG, so it can size to the containing element or be directly sized using CSS:

没有为SVG定义widthheight属性,因此可以将其调整为包含元素的尺寸,也可以使用CSS直接调整尺寸:

#invader {
  display: block;
  width: 200px;
}

#invader path {
  stroke-width: 0;
  fill: #080;
}

See the Pen HTML-Inlined SVG by SitePoint (@SitePoint) on CodePen.

见笔HTML内联SVG由SitePoint( @SitePoint上) CodePen

SVG elements such as paths, circles, rectangles etc. can be targeted by CSS selectors and have the styling modified using standard SVG attributes as CSS properties. For example:

SVG元素(例如路径,圆形,矩形等)可以被CSS选择器作为目标,并使用标准SVG属性作为CSS属性来修改样式。 例如:

/* CSS styling for all SVG circles */
circle {
  stroke-width: 20;
  stroke: #f00;
  fill: #ff0;
}

This overrides any attributes defined within the SVG because the CSS has a higher specificity. SVG CSS styling offers several benefits:

这会覆盖SVG中定义的所有属性,因为CSS具有更高的特异性。 SVG CSS样式具有以下优点:

  • attribute-based styling can be removed from the SVG entirely to reduce the page weight

    可以从SVG中完全删除基于属性的样式,以减少页面权重
  • CSS styling can be reused across any number of SVGs on any number of pages

    CSS样式可以在任意数量的页面上的任意数量的SVG中重复使用
  • the whole SVG or individual elements of the image can have CSS effects applied using :hover, transition, animation etc.

    整个SVG或图像的各个元素都可以使用:hovertransitionanimation等应用CSS效果。

SVG精灵 (SVG Sprites)

A single SVG file can contain any number of separate images. For example, this folders.svg file contains folder icons generated by IcoMoon. Each is contained within a separate <symbol> container with an ID which can be targeted:

单个SVG文件可以包含任意数量的单独图像。 例如,此folders.svg文件包含IcoMoon生成的文件夹图标。 每个都包含在一个单独的<symbol>容器中,其容器具有可以定位的ID:

<svg xmlns="https://www.w3.org/2000/svg">
  <defs>
    <symbol id="icon-folder" viewBox="0 0 32 32">
      <title>folder</title>
      <path d="M14 4l4 4h14v22h-32v-26z"></path>
    </symbol>
    <symbol id="icon-folder-open" viewBox="0 0 32 32">
      <title>open</title>
      <path d="M26 30l6-16h-26l-6 16zM4 12l-4 18v-26h9l4 4h13v4z"></path>
    </symbol>
    <symbol id="icon-folder-plus" viewBox="0 0 32 32">
      <title>plus</title>
      <path d="M18 8l-4-4h-14v26h32v-22h-14zM22 22h-4v4h-4v-4h-4v-4h4v-4h4v4h4v4z"></path>
    </symbol>
    <symbol id="icon-folder-minus" viewBox="0 0 32 32">
      <title>minus</title>
      <path d="M18 8l-4-4h-14v26h32v-22h-14zM22 22h-12v-4h12v4z"></path>
    </symbol>
    <symbol id="icon-folder-download" viewBox="0 0 32 32">
      <title>download</title>
      <path d="M18 8l-4-4h-14v26h32v-22h-14zM16 27l-7-7h5v-8h4v8h5l-7 7z"></path>
    </symbol>
    <symbol id="icon-folder-upload" viewBox="0 0 32 32">
      <title>upload</title>
      <path d="M18 8l-4-4h-14v26h32v-22h-14zM16 15l7 7h-5v8h-4v-8h-5l7-7z"></path>
    </symbol>
  </defs>
</svg>

The SVG file can be referenced as an external, cached resource in an HTML page. For example, to show the folder icon at #icon-folder:

可以将SVG文件引用为HTML页面中的外部缓存资源。 例如,要在#icon-folder处显示文件夹图标:

<svg class="folder" viewBox="0 0 100 100">
  <use xlink:href="folders.svg#icon-folder"></use>
</svg>

and style it with CSS:

并使用CSS设置样式:

svg.folder { fill: #f7d674; }

The method has a couple of drawbacks:

该方法有两个缺点:

  1. It fails in IE9+.

    在IE9 +中失败。
  2. CSS styling only applies to the <svg> element containing the <use>. The fill here makes every element of the icon the same color.

    CSS样式仅适用于包含<use><svg>元素。 此处的fill使图标的每个元素都具有相同的颜色。

To solve these issues, the SVG sprite can be embedded within page HTML, then hidden using display: none or similar techniques. An individual icon can be placed by referencing the ID:

为了解决这些问题,可以将SVG Sprite嵌入到页面HTML中,然后使用display: none隐藏display: none或类似技术。 可以通过引用ID来放置单个图标:

<svg><use xlink:href="#icon-folder"></use></svg>

See the Pen SVG sprites by SitePoint (@SitePoint) on CodePen.

请参阅CodePen上的SitePoint ( @SitePoint )提供的Pen SVG精灵

This works in all modern browsers from IE9+ and it becomes possible to style individual elements within each icon using CSS.

这适用于IE9 +的所有现代浏览器,并且可以使用CSS在每个图标中设置单个元素的样式。

Unfortunately, the SVG set is no longer cached and must be reproduced on every page where an icon is required. The solution (to this solution!) is to load the SVG using Ajax — which is then cached — and inject it into the page. The IcoMoon download provides a JavaScript library, or you could use SVG for Everybody.

不幸的是,SVG集不再被缓存,并且必须在需要图标的每个页面上复制。 解决方案(针对此解决方案!)是使用Ajax加载SVG(然后将其缓存),然后将其注入页面中。 IcoMoon下载提供了一个JavaScript库,或者您可以将SVG用于Everybody

SVG对HTML内容的影响 (SVG Effects on HTML Content)

SVG has long supported:

SVG长期以来一直支持:

  • masks: altering the visibility of parts of an element

    遮罩 :更改元素各部分的可见性

  • clipping: removing segments of an element so a standard regular box becomes any other shape

    剪裁 :删除元素的片段,使标准的常规框变为任何其他形状

  • filters: graphical effects such as blurring, brightness, shadows, etc.

    滤镜 :图形效果,例如模糊,亮度,阴影等。

These effects have been ported to the CSS mask, clip-path, and filter properties. However, it’s still possible to target an SVG selector:

这些效果已被移植到CSS maskclip-pathfilter属性。 但是,仍然可以定位SVG选择器:

/* CSS */
.myelement {
  clip-path: url(#clip);
}

This references an effect within an HTML-embedded SVG:

这引用了嵌入HTML的SVG中的效果:

<svg xmlns="https://www.w3.org/2000/svg" aria-hidden="true" style="position: absolute; width: 0; height: 0; overflow: hidden;">
  <defs>
    <clipPath id="clip">
      <text x="0" y="200" font-family="Arial" font-size="10em" font-weight="800">Text Clip</text>
    </clipPath>
  </defs>
</svg>

to produce effects such as clipped text with an image or gradient background:

产生效果,例如带有图像或渐变背景的剪切文本:

See the Pen SVG clipping by SitePoint (@SitePoint) on CodePen.

请参阅CodePenSitePoint ( @SitePoint )的Pen SVG剪辑

便携式SVG (Portable SVGs)

Finally, standalone SVGs can contain CSS, JavaScript and base64-encoded fonts or bitmap images! Anything outside the realms of XML should be contained within <![CDATA[]]> sections.

最后,独立的SVG可以包含CSS,JavaScript和base64编码的字体或位图图像! XML范围之外的任何内容都应包含在<![CDATA[]]>部分中。

Consider the following invader.svg file. It defines CSS styling with hover effects and a JavaScript animation which modifies the viewBox state:

考虑以下invader.svg文件。 它使用悬浮效果和修改viewBox状态JavaScript动画定义CSS样式:

<svg id="invader" xmlns="https://www.w3.org/2000/svg" viewBox="35.4 35.4 195.8 141.8">
  <!-- invader images: https://github.com/rohieb/space-invaders !-->
  <style>/* <![CDATA[ */
    path {
      stroke-width: 0;
      fill: #080;
    }

    path:hover {
      fill: #c00;
    }
  /* ]]> */</style>
  <path d="M70.9 35.4v17.8h17.7V35.4H70.9zm17.7 17.8v17.7H70.9v17.7H53.2V53.2H35.4V124h17.8v17.7h17.7v17.7h17.7v-17.7h88.6v17.7h17.7v-17.7h17.7V124h17.7V53.2h-17.7v35.4h-17.7V70.9h-17.7V53.2h-17.8v17.7H106.3V53.2H88.6zm88.6 0h17.7V35.4h-17.7v17.8zm17.7 106.2v17.8h17.7v-17.8h-17.7zm-124 0H53.2v17.8h17.7v-17.8zm17.7-70.8h17.7v17.7H88.6V88.6zm70.8 0h17.8v17.7h-17.8V88.6z"/>
  <path d="M319 35.4v17.8h17.6V35.4H319zm17.6 17.8v17.7H319v17.7h-17.7v17.7h-17.7V159.4h17.7V124h17.7v35.4h17.7v-17.7H425.2v17.7h17.7V124h17.7v35.4h17.7V106.3h-17.7V88.6H443V70.9h-17.7V53.2h-17.7v17.7h-53.2V53.2h-17.7zm88.6 0h17.7V35.4h-17.7v17.8zm0 106.2h-35.5v17.8h35.5v-17.8zm-88.6 0v17.8h35.5v-17.8h-35.5zm0-70.8h17.7v17.7h-17.7V88.6zm70.9 0h17.7v17.7h-17.7V88.6z"/>
  <script>/* <![CDATA[ */
    const
      viewX = [35.4, 283.6],
      animationDelay = 500,
      invader = document.getElementById('invader');

    let frame = 0;

    setInterval(() => {
      frame = ++frame % 2;
      invader.viewBox.baseVal.x = viewX[frame];
    }, animationDelay);

  /* ]]> */</script>
</svg>

When referenced in an HTML <img> or CSS background, the SVG becomes a static image of the initial state (in essence, the first animation frame):

在HTML <img>或CSS背景中引用时,SVG会成为初始状态(本质上是第一个动画 )的静态图像:

However, open the image in its own browser tab and all the effects will return.

但是, 在其自己的浏览器选项卡中打开图像 ,所有效果都会返回。

This could be useful for distributing images, demonstrations or small documents which require a level of embedded interactivity.

这对于分发需要一定程度的嵌入式交互性的图像,演示或小型文档可能很有用。

复杂的SVG (Sophisticated SVGs)

SVGs offer a wide range of technical possibilities both within and outside web pages. When combining CSS with SVG, it becomes possible to style and animate the whole image or individual elements in interesting ways.

SVG在网页内外都提供了广泛的技术可能性。 将CSS与SVG结合使用时,可以以有趣的方式对整个图像或单个元素进行样式设置和动画处理。

This article describes ways to manipulate SVG images, but they are regularly used for smaller visual enhancements such as:

本文介绍了处理SVG图像的方法,但是它们通常用于较小的视觉增强,例如:

  • form focus highlights and validation

    表单重点摘要和验证
  • turning a hamburger menu into a an X close icon

    将汉堡菜单变成X关闭图标

  • creating lava-lamp-like morphing.

    产生类似熔岩灯的变形。

Despite the age of SVG technology, web developers are still discovering ways to transform boring block-based pages with subtle effects through using CSS with SVG. Please let us know if you create any interesting examples.

尽管SVG技术已经过时,但Web开发人员仍在探索通过将CSS与SVG结合使用来转换无聊的基于块的页面的方法,从而产生微妙的效果。 如果您创建任何有趣的示例,请告诉我们。

翻译自: https://www.sitepoint.com/css-with-svg/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值