css制作svg
使用CSS制作SVG的方法
CSS可以与SVG结合使用,通过内联样式、外部样式表或直接在SVG元素上应用样式。以下是一些常见的方法:
内联样式
直接在SVG元素的style属性中编写CSS:
<svg width="100" height="100">
<circle cx="50" cy="50" r="40" style="fill: blue; stroke: black; stroke-width: 2;" />
</svg>
外部样式表

通过<style>标签在SVG文件内部定义CSS规则:
<svg width="100" height="100">
<style>
circle {
fill: red;
stroke: black;
stroke-width: 3;
}
</style>
<circle cx="50" cy="50" r="40" />
</svg>
链接外部CSS文件
在SVG文件中引用外部CSS文件(需确保文件路径正确):

<?xml-stylesheet href="styles.css" type="text/css"?>
<svg width="100" height="100">
<circle cx="50" cy="50" r="40" class="my-circle" />
</svg>
在styles.css中定义样式:
.my-circle {
fill: green;
stroke: black;
stroke-width: 4;
}
常用CSS属性
以下是一些常用的CSS属性,可用于SVG元素:
fill:设置填充颜色(如fill: #ff0000;)stroke:设置描边颜色(如stroke: #000000;)stroke-width:设置描边宽度(如stroke-width: 2px;)opacity:设置透明度(如opacity: 0.5;)transform:应用变换(如transform: rotate(45deg);)
动画效果
通过CSS的@keyframes和animation属性可以为SVG添加动画效果:
<svg width="100" height="100">
<style>
@keyframes pulse {
0% { fill: red; }
50% { fill: blue; }
100% { fill: red; }
}
circle {
animation: pulse 2s infinite;
}
</style>
<circle cx="50" cy="50" r="40" />
</svg>
注意事项
- SVG的CSS属性与HTML的CSS属性略有不同,例如
fill和stroke是SVG特有的属性。 - 某些CSS属性在SVG中可能不受支持,需查阅相关文档确认兼容性。
- 使用外部CSS文件时,需确保SVG文件能正确加载CSS文件(某些环境下可能受限)。
通过以上方法,可以灵活地为SVG元素应用样式和动画效果。






