Thursday 20 February 2020

Add Background Colors to SVGs Using the “rect” Element

The advantages of using SVGs in web development are well known. SVGs are small in size, can be made quite accessible, are scalable while maintaining their quality, and can be animated. Still, there is a learning curve. Things, like the syntax of SVG, can be a little tricky and having to hand-alter SVG code sometimes isn’t out of the question.

Most SVG assets allow styling to be applied in predictable ways. For instance, this circle has a hover state that functions much like any other element in the DOM.

However, a problem I've encountered on several front-end projects is being provided a sub-optimal SVG asset by a client, designer, or brand resources site. There isn’t anything “wrong” with these files, but the SVG code requires manual revision to achieve necessary functionality. Instead of requesting new files, it is often easier to tweak them myself. 

Styling SVGs is complicated by the fact that, as XML-based files, they act like HTML in some respects, but not in others. Let’s work with an example provided by Instagram themselves (which is also easily findable on Wikipedia). Because the spaces in between paths act as a sort of transparency this image displays whatever background has been applied behind it.

Why isn’t there a background color on the SVG so we can apply a color change on hover (e.g. svg:hover { background: #888; })? It’s because the paths fill the reverse of the space you would think they would. The negative space renders whatever sits behind this element (<body> in the CodePen examples below). Often this is not a problem and may even be desirable for large background designs to ensure organic transitions between content areas. However, because I am using this SVG as a link, I will need to alter the file so that I can style the space behind it. 

<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">
  <title>Instagram</title>
  <path d="..." transform="translate(0 0)" fill="#fff"/>
  <path d="..." transform="translate(0 0)" fill="#fff"/>
  <path d="..." transform="translate(0 0)" fill="#fff"/>
</svg>

The Instagram logo is a perfect example of an awkward SVG file that requires more CSS finesse than most. Again, there is nothing wrong with this SVG, but it presents some challenges for styling. In order to add a hover state that alters the background, we will need to change the code above.

There are several ways to go about this, but the easiest fix is to add another element behind the image. Because the Instagram icon is rectangular, we can add a <rect> element behind the three foreground paths that comprise this SVG. If the logo was circular or oval, I would have used the <circle> or <ellipse> element. Be sure to set a height and width to match the viewBox when adding this type of element, and use the rx value to round the corners as needed. Rather than adding a class or fill to every path in the SVG element, we can target the <rect> and <path> elements in the CSS file. 

The advantage of this approach is its simplicity. Instead of having to alter multiple files or use JavaScript or third-party JavaScript libraries, we can add one line of code to the SVG code block and style it. 

If, for some reason, you need or just prefer to leave the SVG file alone, you can revise the CSS to achieve similar functionality. 

We could add a background property on the social-link class but, for this tutorial, I will instead use the slightly more complicated, but equally effective, strategy of revising an SVG by applying a pseudo-element to it. In the example below, I have used the ::before pseudo-class to add a shape and the opacity property to make it visible on hover. To avoid having this shape leave a border around the icon, I have made it slightly smaller than the SVG using the height and width properties (calc(100% - 2px)). Then I center the pseudo-element behind the SVG and match the transition property for both element and pseudo-element.

/* Sets the link's dimensions */
.social-link {
  display: block;
  height: 24px;
  position: relative;
  width: 24px;
}

/* Targets the pseudo-element to create a new layer */
.social-link::before {
  background: #fff;
  border-radius: 2px;
  content: "";
  display: block;
  height: calc(100% - 2px);
  opacity: 0;
  position: absolute;
  transition: all 0.2s ease-in-out;
  width: calc(100% - 2px);
}

/* Changes the background color of the pseudo-element on hover and focus */
.social-link::before:hover, .social-link::before:focus {
  background: #000;
}

/* Makes sure the actual SVG element is layered on top of the pseudo-element */
.social-link svg {
  position: relative;
  z-index: 1;
}

/* Makes the background-color transition smooth */
.social-link svg path {
  transition: all 0.2s ease-in-out;
}

/* SVG paths are initially white */
.social-link path {
  fill: #fff;
}

/* The pseudo-elememt comes into full view on hover and focus */
.social-link:hover::before, .social-link:focus::before {
  opacity: 1;
}

/* Fills the SVG paths to black on hover and focus  */
.social-link:hover svg path, .social-link:focus svg path {
  fill: #000;
}

I recommend the above strategies for a quick fix because using vanilla JavaScript or a JavaScript library like vivus.js or raphaeljs is overkill for adding a hover state to an SVG in most cases. However, there are times when modifying an SVG using JavaScript is preferable. Because JavaScript is undoubtedly the most flexible method to change styles, let’s examine what this might look like.

My example separates the JavaScript file, but if you want to add JavaScript inside the SVG element itself, you will need to add a <script> element, just like an HTML file. Be sure to add a CDATA marker to your <script> element to ensure it is parsed as XML.

I’m using jQuery to simplify things a bit and keep CSS as minimal as possible, although for clarity sake, I have added a background property on the social-link class in the CSS file rather than adding it via JavaScript. Notice that this solution targets svg path when altering the CSS method rather than assigning a class to these paths because, in this case, each path should be treated the same.

There are many many ways to style SVGs, but the examples collected in this article are useful and extensible. Strategies for altering SVG files need to be evaluated by an app’s full functionality, but I suspect most front-end developers will find that the <rect> element offers the simplest and most readable solution.

Acknowledgements

Many thanks to Joe Essey and my front-end pals at Nebo Agency Allison Lewis and Nile Livingston (check out Nile’s article, “SVGs for the Web”). 

The post Add Background Colors to SVGs Using the “rect” Element appeared first on CSS-Tricks.



from CSS-Tricks https://ift.tt/2VejpBL
via IFTTT

No comments:

Post a Comment

Passkeys: What the Heck and Why?

These things called  passkeys  sure are making the rounds these days. They were a main attraction at  W3C TPAC 2022 , gained support in  Saf...