如何将 Material 设计图标用作 CSS 背景图像值?

How can I use a Material Design Icon as a CSS background-image value?

我正在使用 materializecss,所以我已经可以使用 material 设计图标。如何在我的 CSS 代码中将它们用作 background-image 值(实际上是 SASS)?

您可以使用 Material Design Icons 的 SVG 代码来设置背景图像,例如:

.selector {
  background-image: url('data:image/svg+xml;utf-8,<svg xmlns="http://www.w3.org/2000/svg" width="50" height="50" viewBox="0 0 24 24"><path fill="%232196F3" d="M 5,3L 19,3L 20.7359,6L 20.7304,6C 20.9018,6.29149 21,6.63428 21,7L 21,19C 21,20.1046 20.1046,21 19,21L 5,21C 3.89543,21 3,20.1046 3,19L 3,7C 3,6.638 3.09618,6.29846 3.26437,6L 3.26135,6L 5,3 Z M 5.57294,4L 5,5L 5,5L 19,5L 18.4303,4L 5.57294,4 Z M 7,12L 12,17L 17,12L 14,12L 14,10L 10,10L 10,12L 7,12 Z "></path></svg>');
}

A fiddle

我在制作 fiddle 时注意到/被提醒的怪癖:

  • 没有xmlns属性好像不行
  • 填充或其他地方的 # 需要使用 %23 进行转义(或改用 rgb(a) 值)
  • 您可能需要根据需要调整宽高和viewBox属性(是否填充区域,是否重复(也可以用background-repeat影响)等)

如果您使用 Material 图标字体,您可以使用的另一种技术是使用 :before:after 伪选择器 + html entities.

CSS (codepen example)

    /* imports the font */
    @import url("https://fonts.googleapis.com/icon?family=Material+Icons");

    /* adds icon in front of the element */
    .someclass:before { 
        /* https://github.com/google/material-design-icons/blob/master/iconfont/codepoints */
        content: "\E3E7"; 
        font-family: "Material Icons"; 
    }

(这里是link到icon codes

它不完全是 background-image 但仍然有用。