Website Logo. Upload to /source/logo.png ; disable in /source/_includes/logo.html

Up and Running with SVG

An SVG primer for everyone. Created by Mijingo.

Styling SVG with CSS

Up until this point we’ve done our SVG manipulations using standard SVG attributes (and a little bit of CSS). In this section, we’re going to cover how to manipulate SVG with CSS.

Styling SVG with CSS can be done a few different ways:

  • using the style attribute to attach style rules to an individual element,
  • adding a class attribute and then defining styles in an external or in-page stylesheet, and
  • using inline stylesheets, which are nested right in the svg element.

The first are probably most familiar to you. The third one makes the SVG self-contained (the styles are all bundled up in the markup) but will be a maintenance nightmare if you ever need to override or update the styles from an external CSS file.

For our examples, we’ll use styles via the class attribute, which are referenced in an external stylesheet.

Overriding SVG attributes

In our SVG examples up to this point we have made any style changes using SVG attributes like fill. There are others like stroke, fill-opacity, and stroke-width for the SVG shape elements. We can easily override these in our CSS.

Let’s say we wanted to create a monochrome version of our nested square logo from the earlier examples. One way to do that is to override the fill attribute on the two blue square with a different color.

<svg class="logo" width="400" height="400" viewBox="0 0 400 400">
  <rect class="mono" x="0" y="0" width="400" height="400" fill="#56A0D3" />
  <rect x="50" y="50" width="300" height="300" fill="#ffffff" />
  <rect class="mono" x="100" y="100" width="200" height="200" fill="#56A0D3" />
  <rect x="150" y="150" width="100" height="100" fill="#fff" />
</svg>

And the Sass:

.logo {
  .mono {
    fill: #000;
  }
}

View Intro to SVG: Example 10

We could also implement our handy g element to group our rect elements together and then override them all with one single class applied to the g element to convert the logo to monochrome.

<svg width="400" height="400" viewBox="0 0 400 400">
  <g class="mono">
  <rect class="color" x="0" y="0" width="400" height="400" fill="#56A0D3" />
  <rect x="50" y="50" width="300" height="300" fill="#ffffff" />
  <rect class="color" x="100" y="100" width="200" height="200" fill="#56A0D3" />
  <rect x="150" y="150" width="100" height="100" fill="#fff" />
  </g>
</svg>

And the Sass:

.mono {
    .color {
      fill: #000;   
    }
}

Ready to learn more?

Get the Full Video Course