Skip to main content

Archive

Show more

Styling SVG with CSS

Styling SVG with CSS

SVG (Scalable Vector Graphics) elements can be styled using CSS (Cascading Style Sheets) to change their appearance, such as colors, strokes, fills, and other visual properties. By applying CSS styles to SVG elements, you can customize the look and feel of your graphics to match the design of your website or application. Here's how to style SVG with CSS:


1. Inline CSS

You can apply CSS styles directly to SVG elements using the style attribute. This allows you to define styles inline with the SVG markup.

Example:

<svg width="200" height="100">
  <circle cx="50" cy="50" r="40" style="fill: blue; stroke: black; stroke-width: 2px;" />
</svg>

In this example, the circle element is styled with a blue fill color, a black stroke, and a stroke width of 2 pixels.


2. External CSS

You can also apply CSS styles to SVG elements using external CSS files. Define CSS rules for SVG elements in your external stylesheet and link the stylesheet to your HTML document.

Example:

circle {
  fill: red;
  stroke: blue;
  stroke-width: 3px;
}

Link the external stylesheet in your HTML document:

<link rel="stylesheet" type="text/css" href="styles.css" />

This example applies styles to all circle elements, setting the fill color to red, the stroke color to blue, and the stroke width to 3 pixels.


3. Selectors

When styling SVG elements with CSS, you can use selectors to target specific elements or groups of elements. Use element names, IDs, classes, or attribute selectors to apply styles selectively.

Example:

#myCircle {
  fill: green;
}

.circle {
  stroke: orange;
}

In this example, the #myCircle selector targets an SVG element with the ID "myCircle" and sets its fill color to green. The .circle selector targets SVG elements with the class "circle" and sets their stroke color to orange.


4. Conclusion

Styling SVG with CSS allows you to customize the appearance of SVG graphics to suit your design requirements. Whether applying styles inline or using external CSS files, CSS provides a flexible and powerful way to enhance the visual presentation of your SVG content.

Comments