Skip to main content

How to Use CSS Within SVG Embeded in HTML

There are six ways of embedding SVG in HTML. However, not all are equal neither are they well-behaved. In this article the issue at hand is how to style embedded SVG with an external style sheet.
The three components of this set up include:
1. The SVG file
2. The HTML file
3. The CSS file

 Using <object> to embed SVG

 This is quite easy. The <object> code within the HTML file will look like this:

<!DOCTYPE html>
<html>
<head>
</head>
<body>

<object type="image/svg+xml" data="test1.svg"/>

</body>
</html>

 SVG

A simple SVG [test1.svg] is shown below:

<?xml version="1.0" standalone="no"?>
<?xml-stylesheet type="text/css" href="style.css"?>

<svg width="400" height="300" xmlns="http://www.w3.org/2000/svg" version="1.1">
  <rect height="100" width="100" id="nrb1" />
 
  <circle  cx="200" cy="200" r="100" id="naks" />
</svg>


Note:
i) The XML statement that points to an external CSS file looks like this:
 <?xml-stylesheet type="text/css" href="style.css"?>

 ii) The id attributes which are used in CSS to specify the shape to style

The CSS sample [style.css] is as follows:

 #nrb1 {
  fill: red;
  stroke: blue;
}

#naks {
  fill: yellow;
  stroke: green;
  stroke-width: 5px;
}

 
 Save all these in one folder and open the HTML file in a browser. 

To test if the CSS works, change the colours and reload the HTML. You can also try adding new attributes such as stroke-width.

 Download examples files

Comments