Комментарии (1)
🐱
claude-haiku-4.5PrepBro AI26 мар. 2026 г.(ред.)
Ответ сгенерирован нейросетью и может содержать ошибки
Стилизация SVG — применение стилей к векторной графике
Стилизация SVG — это процесс применения CSS и встроенных стилей к SVG элементам для изменения их внешнего вида. SVG элементы можно стилизовать как обычные HTML элементы, но с дополнительными специфичными свойствами.
SVG как встроенный код
<!-- Встроенный SVG в HTML -->
<svg width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<!-- Можно применять CSS классы -->
<circle class="my-circle" cx="50" cy="50" r="40" />
<rect class="my-rect" x="10" y="10" width="30" height="30" />
</svg>
<style>
.my-circle {
fill: blue;
stroke: red;
stroke-width: 2;
}
.my-rect {
fill: green;
opacity: 0.8;
}
</style>
Основные SVG свойства для стилизации
// React компонент с встроенным SVG
export function StyledSVG() {
return (
<svg width="200" height="200" viewBox="0 0 200 200">
{/* fill — цвет заполнения */}
<circle cx="50" cy="50" r="40" fill="blue" />
{/* stroke — цвет обводки */}
<rect x="100" y="10" width="80" height="80" fill="none" stroke="red" />
{/* stroke-width — толщина обводки */}
<line x1="10" y1="150" x2="190" y2="150" stroke="black" strokeWidth="3" />
{/* stroke-linecap — форма конца линии */}
<line x1="10" y1="170" x2="190" y2="170" stroke="black" strokeWidth="4" strokeLinecap="round" />
{/* stroke-linejoin — форма углов линии */}
<polyline points="10,190 50,150 90,190" stroke="blue" fill="none" strokeWidth="2" strokeLinejoin="bevel" />
{/* opacity — прозрачность */}
<circle cx="150" cy="150" r="30" fill="purple" opacity="0.5" />
</svg>
);
}
CSS для SVG элементов
/* Базовая стилизация */
svg {
width: 100%;
height: auto;
}
/* Стилизация элементов внутри SVG */
svg circle {
fill: navy;
stroke: white;
stroke-width: 2;
}
svg rect {
fill: teal;
transition: fill 0.3s ease;
}
/* Интерактивные эффекты */
svg rect:hover {
fill: orange;
}
/* Разные стили для разных классов */
.icon-primary {
stroke: blue;
fill: lightblue;
}
.icon-secondary {
stroke: gray;
fill: lightgray;
}
/* SVG фильтры */
.icon-shadow {
filter: drop-shadow(2px 2px 4px rgba(0, 0, 0, 0.3));
}
.icon-blur {
filter: blur(2px);
}
Стилизация с пользовательскими свойствами (CSS Variables)
export function DynamicSVG({ color, size }: { color: string; size: number }) {
return (
<svg
width={size}
height={size}
viewBox="0 0 100 100"
style={{
"--svg-color": color,
"--svg-size": `${size}px`,
} as React.CSSProperties}
>
<style>{`
.dynamic-circle {
fill: var(--svg-color);
}
`}</style>
<circle cx="50" cy="50" r="40" className="dynamic-circle" />
</svg>
);
}
// Использование
<DynamicSVG color="red" size={100} />
<DynamicSVG color="blue" size={150} />
SVG в тегах и компонентах
// SVG как компонент
export function IconCheck({ className, color = "currentColor" }: { className?: string; color?: string }) {
return (
<svg
className={className}
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke={color}
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
>
<polyline points="20 6 9 17 4 12" />
</svg>
);
}
// Использование с Tailwind
<IconCheck className="w-6 h-6 text-green-500" color="currentColor" />
// SVG как фоновое изображение
const Background = () => (
<div
style={{
backgroundImage: "url(\"data:image/svg+xml,%3Csvg...\")",
backgroundSize: "cover",
}}
>
Content
</div>
);
Анимация SVG
import { motion } from "framer-motion";
export function AnimatedSVG() {
return (
<svg width="100" height="100" viewBox="0 0 100 100">
<style>{`
@keyframes rotate {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
.rotating-circle {
animation: rotate 2s linear infinite;
transform-origin: 50px 50px;
}
`}</style>
<circle cx="50" cy="50" r="40" fill="blue" className="rotating-circle" />
</svg>
);
}
// Или с Framer Motion
export function FramerAnimatedSVG() {
return (
<motion.svg
width="100"
height="100"
viewBox="0 0 100 100"
animate={{ rotate: 360 }}
transition={{ duration: 2, repeat: Infinity }}
>
<circle cx="50" cy="50" r="40" fill="blue" />
</motion.svg>
);
}
Специфичные SVG свойства
export function AdvancedSVG() {
return (
<svg width="300" height="300" viewBox="0 0 300 300">
{/* stroke-dasharray и stroke-dashoffset для пунктирных линий */}
<circle
cx="150"
cy="150"
r="100"
fill="none"
stroke="blue"
strokeWidth="4"
strokeDasharray="628"
strokeDashoffset="0"
/>
{/* stroke-miterlimit для управления углами */}
<polyline
points="50,50 100,100 150,50"
fill="none"
stroke="red"
strokeWidth="2"
strokeMiterlimit="4"
/>
{/* marker для стрелок на концах */}
<defs>
<marker
id="arrowhead"
markerWidth="10"
markerHeight="10"
refX="9"
refY="3"
orient="auto"
>
<polygon points="0 0, 10 3, 0 6" fill="black" />
</marker>
</defs>
<line
x1="10"
y1="10"
x2="100"
y2="100"
stroke="black"
strokeWidth="2"
markerEnd="url(#arrowhead)"
/>
{/* Градиенты */}
<defs>
<linearGradient id="grad1" x1="0%" y1="0%" x2="100%" y2="100%">
<stop offset="0%" stopColor="red" />
<stop offset="100%" stopColor="blue" />
</linearGradient>
</defs>
<circle cx="200" cy="150" r="50" fill="url(#grad1)" />
</svg>
);
}
Использование SVG в стилях
/* Как фоновое изображение */
.icon {
background-image: url("icon.svg");
background-size: contain;
background-repeat: no-repeat;
width: 40px;
height: 40px;
}
/* Как маска */
.masked-element {
-webkit-mask-image: url("mask.svg");
mask-image: url("mask.svg");
}
/* Как клип */
.clipped-element {
clip-path: url("#svg-clip");
}
Практический пример: Иконка с наведением
export function InteractiveIcon() {
return (
<style>{`
.icon-button {
cursor: pointer;
transition: all 0.3s ease;
}
.icon-button:hover svg {
filter: drop-shadow(0 0 8px rgba(59, 130, 246, 0.5));
}
.icon-button:hover svg circle {
fill: rgb(59, 130, 246);
}
.icon-button:active svg {
transform: scale(0.95);
}
`}</style>
<button className="icon-button">
<svg width="40" height="40" viewBox="0 0 40 40">
<circle cx="20" cy="20" r="18" fill="lightblue" stroke="blue" strokeWidth="2" />
<text x="20" y="25" textAnchor="middle" fontSize="20" fill="blue">
★
</text>
</svg>
</button>
);
}
Важные замечания
- viewBox — определяет координатную систему SVG
- preserveAspectRatio — как масштабировать SVG
- currentColor — использует текущий цвет текста
- CSS заходит в приоритет — встроенные стили перебивают CSS
- CORS — для внешних SVG файлов нужно соответствующее разрешение