Css background svg path

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 ( 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.

Читайте также:  Python argument with asterisk

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 element behind the three foreground paths that comprise this SVG. If the logo was circular or oval, I would have used the or 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 and 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

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 element, just like an HTML file. Be sure to add a CDATA marker to your 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 element offers the simplest and most readable solution.

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”).

Источник

How to add SVGs with CSS (background-image)

There are TWO methods for displaying SVG images as a CSS background image:

Notice with this method we have to treat the SVG code before it will work. In the example, we convert the SVG to a Data URI. You could even convert it to Base64, but that will result in a messier, longer code blob. It is a best practice to avoid Base64 in this case.

Tip: Use this SVG to CSS converter tool to quickly convert your SVG code into a data URI.

After you place your file path or SVG code into the background-image property, you can further tweak how the background displays. You see, the great thing about using an SVG as a CSS background-image is that they can be styled with CSS background properties.

The CSS background-image properties

Let’s review all the properties related to background-image and what they do.

  • Background-attachment:
    Example values: scroll; fixed; local;
    The attachment specifies how the background moves relative to the user’s screen. When the user scrolls, the background can scroll along with a given section, or stay put ( fixed ).
  • Background-position:
    Example values: center; top left; 50% 50%; right 30px bottom 15px;
    The background-position determines where the image is displayed within its container. The center keyword is great with large backgrounds and at making patterns symmetrical. With smaller backgrounds, you may reach for a combo of keywords and lengths to place the background image more precisely.
  • Background-size:
    Example values: cover; contain; 500px 250px; auto;
    This controls how big or small the image displays. A value of cover forces the image to fill its entire containing element in proportion, and either the excess width or height will get clipped. A value of contain is similar in that it fills its container in proportion, but without clipping. You can also provide a specific width and height value.
  • Background-repeat:
    Example values: no-repeat; repeat; repeat-x;
    The background-repeat property allows you to tile the background image into a pattern.
  • Background-color:
    Example values: red; #F00; rgb(0,255,165);
    SVGs are a transparent image format and if the SVG elements do not cover the entire viewBox, the background color will be visible behind your SVG.
  • Background-origin:
    Example values: border-box; padding-box; content-box;
    The origin determines the boundary of the background’s container. Border-box will stretch the background area for the entire container, while the padding-box and content-box values shrink the background area within the border and inside the padding respectively.
  • Background-clip:
    Example values: border-box; padding-box; content-box;
    Similar to background-origin , this property defines the background area, with one difference: the background doesn’t resize, but instead crops the background image to fit in the assigned boundary.
  • Background-blend-mode:
    Example values: multiply; screen; overlay, color-dodge, color;
    This property blends the colors of the target background with what is visible behind the target element, blending into a single colorful result. The blend modes are essentially the browser version of Photoshop’s blending modes.

Layering multiple background images

Background-image can hold multiple background image layers to achieve cool effects. To create these image layers, comma-separate each image value in a single background-image property. Then when you use any related background properties, comma-separate those varied values to coincide with the images, or instead use a single value which will apply to all images the same.

background-image: url( '/path/image-1.svg' ), url( '/path/image-2.svg' ), url( '/path/image-3.svg' );

You can mix images, SVG data URIs, and CSS gradients. But you need to overlap images with transparency or take advantage of the background-blend-mode discussed above. Otherwise you will only see one background. The first image is on top of the background stack.

Let’s mix a few backgrounds now, and see what we get. First I headed over to the homepage of SVGBackgrounds.com to find a few quick backgrounds to layer together. Here is the code and results:

BUT, this technique prevents the need to layer div containers to achieve a layer effect. Let’s try again, this time to make a simpler one that looks useable. Let’s place a pattern over a cool image texture.

Much better!

I could definitely see something more like this being used in a real-world project. Subtle backgrounds are always nice.

Wrapping up about SVGs in CSS background-images

We looked at how to add SVGs into the CSS property background-image . With all the related background properties and the fact you can layer backgrounds, there is little that can’t be achieved. This way of adding website backgrounds is powerful.

), the creator behind SVG Backgrounds. Hire me to help you with design on your website or app.

), the creator behind SVG Backgrounds. I produce free and paid resources every few months, sign up for alerts.

Источник

Оцените статью