Archive for CSS

Jul
31

CSS vs. SVG: Graphical Text

Posted by: | Comments (0)

This post is the first in a series of posts exploring techniques and examples that can be achieved using both CSS and SVG, and compares them both. Since I am biased to SVG, this series is really intended to prove that SVG — because of its nature as both an image and a document format — is simply better than CSS when it comes to solving certain design problems on the web. But to keep an objective point of view, we will be weighing the pros and cons of each technique and find out where and when CSS or SVG can serve as a better tool to the design goals at hand.

In this article, we’re going to go over a few techniques for creating graphical text effects for the web using CSS and using SVG.

Graphical Text Effects with CSS

The Old CSS Way

Some years ago, we used to hack our way into creating visually appealing text on the web by not creating that text on the web, but by simply placing an image of that effect in stead of a piece of text that we would otherwise want to be graphical.

This concept of showing an image of the text where the text would show on the screen makes it possible to display a nice textual effect when we did not have the technology to achieve it (although that’s not entirely true because SVG has been around for way longer than that), and the technique is known as the “image replacement” technique.

Assume you have an h1 heading you want to replace with the image showing the same piece of text with that impressive graphical effect. The way you would do that using CSS looks like this:

h1.hide-text {
    text-indent: 100%;
    white-space: nowrap;
    overflow: hidden;
    background-image: url(…);
}

The text indentation makes sure the content of the heading exceeds its own boundaries and overflows them, and the hidden overflow value makes sure it gets cut off outside those boundaries and does not show up. So, you end up with a rectangular area (of the h1) that has no text showing inside of it.

Then the heading gets a background image which, predictably, is the image of that text that you would have created in a graphics editor such as Photoshop, for example.

So, the rectangular area of the heading is rendered and shown on the screen, without the text content inside it, and with the background image showing the graphical text inside. Neat. That’s all you needed to do to display nice graphical text effects.

The above method is called the Kellum Method since it was written by Scott Kellum and it replaced an older, not very good method that developers used before. Indeed, there were quite a few image replacement techniques back then, and the Kellum method replaced most of them because it was the “best” among the options available back then.


Not only does this technique make the text unselectable by the user (because the text inside the image cannot be selected), but it is also a hack, in the end, so new CSS properties were introduced to help achieve similar effects without having to resort to image replacement techniques..

The New CSS Ways

There are many, many text effects that can be created, including squiggly text effects that Lucas Bebber wrote about in a previous article here on the Dreamweaver blog. That said, the most commonly used text effects are either texture-filled text effects or simply textured text—or text that seemingly blends with its background.

Texture-filled Text

css-background-clip

Using the CSS background-clip property, we can fill a piece of text with a texture from an image. This property determines an element’s background painting area, which is the area within which the background is painted. By default, the background extends all the way to the border of an element with a default value of border-box, and it can take other values like padding-box and content-box, which are self-explanatory.

The background-clip property was extended in Webkit with a fourth value, text, which causes the background image to clip to foreground text. Then, by giving the text a transparent color using the Webkit-only property -webkit-text-fill-color, the background image will show through the text, thus completing the clipping effect.

For example, to clip an element’s background to the contents of the text inside of it, you would give that element a class and then apply these styles to it:

.clippedElement {
  /* background image that will serve as text fill */
  background: url(path/to/your/image.jpg) no-repeat center center;
    /* -webkit-background-clip clips the background of the element to the text */
    -webkit-text-fill-color: transparent; /* overrides the white text color in webkit browsers */
    -webkit-background-clip: text;

  /* general styles */
    background-size: 100% auto;
    color: #fff;
    text-align: center;
    padding: 2em;
}

Unfortunately, as you can see from the prefixes used, these properties currently only work in the handful of browsers that support them, so they won’t work in Firefox or IE, for example.

So, if we were to go back to our previous h1 that has a background applied to it, we wouldn’t have to hide the text anymore to show texture-filled text on the page. Instead, we wrap the heading in a div, give that div the background image that we want to use as a fill for the text, and then clip that background to the shape of the text using the above CSS properties.

The following is a live demo of this technique in action. Make sure you view it in Chrome, Safari or Opera to see it working.

See the Pen 362ec4667abd7180c298f0f1061573ed by Sara Soueidan (@SaraSoueidan) on CodePen.

For non-supporting browsers, you can revert to a simple image with text on top of it; just make sure the text color goes well with the background and does not cause any visual reading problems.

Note that the background image can be any image, including a CSS gradient because that, too, is an image. You can learn all about CSS gradients here.

 

Textured Text (Blending with Background)

Next, we’re going to use CSS masks to create the following effect where the text has some of its parts “erased” off:

css-mask

When using CSS masks, we’re making the text take the shape of its mask image, instead of making the image take the shape of (or be clipped to the shape of) the text.

The above effect uses the following mask image that I borrowed from this article I wrote on Codrops over a year ago. The image is used as a mask to mask areas of the text so that the background behind it shows through. If you choose the proper mask texture that goes with that of the background, you can achieve a nice seamless blending effect. Our mask image is made up of a bunch of “splashes” of paint. For sake of simplicity, we’re not doing any “blending” per se, only applying the splatter texture to the text.

splatter-mask

The mask image can be any image you want, including a gradient.

When you apply a CSS mask to your text, or to any other content, the text will be visible where the black areas are, and the parts where the mask image is transparent the text will not show. This is because the default type of the mask image used in CSS is an alpha mask, not a luminance mask; and since we provided an alpha mask, the dark areas will be used to define the painting area for the text.

In the case of a gradient that goes from black to transparent, for example, the masked element would be fully opaque where the gradient is black, then becomes translucent and gradually fades out where the gradient becomes transparent.

The CSS mask-image property is used to reference the mask image that we will apply to our text.

h1 {
    /* the line that applies the splatter effect */
    mask-image: url(../img/splatter-mask_1.png); 

/* any general styles go here like font family, alignment, etc. */
}

At the time of writing of this article, CSS masks are not supported too well either. Firefox only supports SVG masks and webkit browsers require the webkit prefix and only support two properties of the entire Masking specification. For a detailed look at browser support, refer to this support table.

So this is yet another way to accomplish textured text in CSS, but it is also not reliable at this time.

The following is a live demo of the above technique (view in a webkit-based browser):

 

See the Pen 75a243d2c0072a8f0bea903a0f8f9576 by Sara Soueidan (@SaraSoueidan) on CodePen.

If you want to try the gradient mask image out, replace the mask-image declaration with this line:

mask-image: linear-gradient(black, transparent);

to see the text fade out. This is how a texture can be applied to an element or a piece of text using CSS.

With SVG, things are looking much better…

Graphical Text with SVG

SVG is awesome. (I had to say that.) Now, for the sake of brevity, we will dig right into the code and explain it as we go.

When working in SVG, both the text and the effects we apply to it will be defined inside an <svg> element…

Texture-filled Text

To fill a piece of text with a texture, you need to define that texture—whatever it is—first, and then use it as a fill color on the element of your choice—which, in our case, is a piece of SVG text.

For this example, we will define a linear gradient and use it as a fill for our text.

gradient-text

The code for that looks like this:

<svg xmlns=“http://www.w3.org/2000/svg”  viewBox=“0 0 1250 400” width=“1250” height=“400”> 
    <title>Gradient-filled Text</title>
    <!— Source: http://lea.verou.me/2012/05/text-masking-the-standards-way/ —>
    <defs>
       <linearGradient id=“filler” x=“0%” y=“100%”>
           <stop stop-color=“gold” offset=“0%”></stop>
             <stop stop-color=“purple” offset=“20%”></stop>
           <stop stop-color=“deepPink” offset=“40%”></stop>
           <stop stop-color=“orange” offset=“60%”></stop>
           <stop stop-color=“yellow” offset=“80%”></stop>
           <stop stop-color=“skyblue” offset=“100%”></stop>
      </linearGradient>
    </defs>
    <text x=“100” y=“70%” font-size=“205” fill=“url(#filler)”> Radiant Text</text>
</svg>

Note: we have defined specific height and width for the svg, but to make sure the SVG is responsive, override the default dimensions in CSS and make them percentage-based. You can learn all about making SVGs responsive here.

The <defs> element is used to define our texture—a linearGradient in this case. The gradient gets an ID that is then referenced on our <text> element inside the fill attribute, thus filling the text with the gradient image. Could it get any more semantic?!

Here is a live demo of the above code:

See the Pen Adobe css vs svg text by Sara Soueidan (@SaraSoueidan) on CodePen.

The texture can be anything—even an SVG <image> element that would reference any external image you want (JPEG, PNG, GIF!). It can also be an SVG <pattern>.

And because an SVG is literally a graphic, make sure to include a title so that it’s accessible by screen readers. The title is to the svg what an alt attribute is to an img element in HTML.

 

Applying Texture to Text (Blending with Background)

Similar to the previous technique, combining the concept in the CSS masking section and the definitions inside SVG, we can apply texture to an SVG <text> by first defining the mask we want and then referencing it using the mask attribute (instead of fill).

In this example, I want to apply a bite mark effect to a piece of text that says “nom nom nom”, as shown in the image below.

 

svg-mask-demo

The result of applying an SVG bite marks mask to a piece of text.

 

First I created the bite marks in my graphics editor by drawing them on top of the text that I was going to add the effect to. It helps to do this visually so you make sure that the bite marks end up applied where you expect them to be.

Then, I exported the shapes as SVG and used them to define the shape of the mask inside a <defs> element like so:

<svg viewBox=“0 0 900 400”>
  <defs>
    <mask id=“mask”>
      <rect x=“0” y=“0” width=“100%” height=“100%” fill=“#fff”></rect>
            <path fill=“#000” d=“…”></path>
            <path fill=“#000” d=“…”></path>
            <path fill=“#000” d=“…”></path>
            <path fill=“#000” d=“…”></path>
            <path fill=“#000” d=“…”></path>
            <path fill=“#000” d=“…”></path>
            <path fill=“#000” d=“…“></path>
            <path fill=“#000” d=“…“></path>
    </mask>
  </defs>

  <text font-size=“230” fill=“#FF481E” mask=“url(#mask)”>
    <tspan x=“0” y=“150”>nom</tspan>
    <tspan y=“280” x=“150”>nom<tspan>
    <tspan y=“400” x=“350”>nom<tspan>
  </text>
</svg>

There is an important note to remember here: in SVG, unlike in CSS, the element will—by default—be drawn where the mask is white, and it will not be drawn where the mask is black. Any value in between black and white will render the element translucent such that: the closer to white (#ffffff) the color of the masking shape is, the more opaque the shape using the mask will be. The closer the color of the masking shape is to black (#000000), the more transparent the shape using the mask will be.

So, in the above example, I gave the bite shapes a black fill and added a rectangle that fills the entire SVG and coloured it white; this will make sure the text will be fully visible anywhere on the canvas except where the bite marks are in black.

And here is a demo that shows the result of the above code in action:

 

See the Pen adobe css vs svg text by Sara Soueidan (@SaraSoueidan) on CodePen.

And that is all you need to do to apply a texture to text in SVG. You can use a gradient, an image, or any other shape or pattern to mask your text out. And since there are a lot of element options that can go inside that <defs>, you can create some quite interesting effects such as animated textures and fills!…

Animated Text Fills with SVG

Not only does SVG provide us with better support and modularity (because the text and its effect are wrapped inside one image to form our text “graphic”), but the nature of the SVG code allows it to also be animated.

When you define a fill for an element inside <defs>, you can also animate that fill and then, when it is applied to the element, it will still animate as a fill as well. Meaning that effects like the ones in the following image become very much possible:

animated-fills

Animated text fills using SVG.

One of the above example uses a GIF image as a fill (!), so the animated GIF stays animated inside the text it is used to fill as well.

The above examples are all created and explained in this excellent article on Codrops, so make sure you check them out for details including browser support and fallbacks.

Final Words

Until CSS masks are more widely supported and maybe other browsers implement the background-clip: text value, SVG is definitely the best way to create textured text effects on the web.

As a matter of fact, I’d personally still use SVG even if CSS got better for the animation capabilities alone. I also love the fact that the text and its effect are “encapsulated” in one image that can be copied and dropped anywhere, making it more reusable and flexible. And, most importantly, SVG text is fully accessible, searchable, selectable and 100% semantic.

Stay tuned for the next post tackling yet another use case where both CSS and SVG could be used, comparing both and helping you make a better decision which one to choose.

I hope you liked this article and found it useful. Thank you for reading!

Comments (0)

In this post, I’m going to walk you through how to create a squiggly text effect using SVG Filters and CSS. This effect can be useful when you want to make things a bit more playful. This tutorial can also serve as an introduction to, and exploration of, SVG filters.

SVG Filters

SVG Filters are filter effects that were originally developed for SVG, but can be applied to regular DOM elements through the CSS filter property. They allow for much more flexibility than regular CSS filters due to the ability to chain filters together, as well as the greater variety of base effects (which are called primitives).

To illustrate how they work, here is a drop shadow effect created with SVG Filters:

<div class="element"></div>

<!-- We need to declare our SVG filters inside
an SVG element -->
<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
  <defs>
    <filter id="drop-shadow">
      <!-- Get the element's graphic, through the SourceGraphic
        keyword in the 'in' attribute, apply a blur filter, and
        name the output using the 'result' attribute -->
      <feGaussianBlur in="SourceGraphic" stdDeviation="7" result="shadow" />

      <!-- Get the previous output, shift its position, and output
        with the same name -->
      <feOffset in="shadow" dx="3" dy="4" result="shadow" />

      <!-- Darken the result of the previous filters -->
      <feColorMatrix in="shadow" mode="matrix" values="0 0 0 0 0  0 0 0 0 0  0 0 0 0 0  0 0 0 0.6 0" result="shadow" />

      <!-- Put the original graphics atop the shadow we made -->
      <feBlend in="SourceGraphic" in2="shadow" />
    </filter>
  </defs>
</svg>

Then we just apply it to an element with CSS:

.element{
  filter:url('#drop-shadow');
}

See the Pen svg drop shadow demonstration by Lucas Bebber (@lbebber) on CodePen.

More information about SVG Filters can be found here.

Squiggle It Up

There are two filter primitives we need in order to make the squiggle effect work: feDisplacementMap, which distorts an object based on an image map, and feTurbulence, which will generate the noisy image map we need for the distortion.

feDisplacementMap takes two inputs: in, which will be the image to be distorted, and in2, which is an image that tells the filter where to distort, based on its lightness. Another important attribute is the scale parameter, which sets the maximum distortion the filter will apply.

displacement

The feTurbulence filter generates a random, noisy image. It has several parameters that help us adjust the result to our needs, and a seed attribute that lets us change the base number it uses for its randomization.

This filter will be useful in creating the displacement maps we need in order to make a nice wiggle effect.

See the Pen feTurbulence demonstration by Lucas Bebber (@lbebber) on CodePen.

To use both filters together is fairly simple. We make the feTurbulence filter first, then we take its output and put it into our feDisplacementMap‘s in2 attribute.

<filter id="squiggly">
      <feTurbulence baseFrequency="0.02" numOctaves="3" result="noise" seed="2"/>
      <feDisplacementMap in="SourceGraphic" in2="noise" scale="10" />
</filter>

See the Pen Squiggly Text Experiment by Lucas Bebber (@lbebber) on CodePen.

Animating

Now, we could simply animate the seed parameter (which sets its randomization) of our feTurbulence filter and call it a day. The problem is that this is bad for performance; the browser will have to generate a new random image every frame, and then make a new feDisplacementMap based on it.

What we can do to get around that is to simply make a bunch of copies of the entire filter with slightly different parameters, and alternate between then. This way the browser will only have to render most of the animation once.

<filter id="squiggly-0">
  <feTurbulence baseFrequency="0.02" numOctaves="3" result="noise" seed="0"/>
  <feDisplacementMap id="displacement" in="SourceGraphic" in2="noise" scale="6" />
</filter>
<filter id="squiggly-1">
  <feTurbulence baseFrequency="0.02" numOctaves="3" result="noise" seed="1"/>
  <feDisplacementMap in="SourceGraphic" in2="noise" scale="8" />
</filter>
<!-- make as many copies as you want, changing the seed and the scale attributes -->
@keyframes squiggly-anim {
  0% {
    filter: url("#squiggly-0");
  }
  25% {
    filter: url("#squiggly-1");
  }
  50% {
    filter: url("#squiggly-2");
  }
  75% {
    filter: url("#squiggly-3");
  }
  100% {
    filter: url("#squiggly-4");
  }
}
.squiggly{
  animation: squiggly-anim 0.4s linear infinite;
}

See the Pen Squiggly Text Experiment by Lucas Bebber (@lbebber) on CodePen.

And with that we are done! Please note that these filters are not supported by every browser, and even fewer support animating them like this. These effects can also be quite heavy, so be careful!

Comments (0)
Jun
23

Creating Realistic Text with CSS

Posted by: | Comments (0)

Today I’ll show how to make a realistic text effect with a tilt-shift blur, using CSS and JavaScript. This effect is nice for mockups, demos, and the like.

See the Pen Kinda Realistic Text by Lucas Bebber (@lbebber) on CodePen.

How it Works

First, let me explain how the technique works. Since there’s no tilt-shift filter effect, we’ll have to cheat a bit. We start by putting our text onto a 3D plane. how1 Now, here’s the trick: we clone that plane multiple times, and then rotate (3d rotation, on the X axis) each one by a small amount around an arbitrary origin, which will be the focal point. We also have to reduce the opacity of each layer, since we are overlaying them. how2 Finally, in order to make the blur smooth, we just make more clones of the text and reduce the angle difference between each layer. how3 Now, let’s see how to implement this effect…

The Code

    <div class="container">
      <div class="layer">
        Insert your text here.
      </div>
    </div>
    .container{
      position:absolute;
      transform-origin:50% 0%;
      transform: perspective(1000px) scale(0.9) rotateX(60deg);
      transform-style:preserve-3d;
    }
    .layer{
      position:absolute;
      top:0;
      left:0;
      transform-origin:50% 30vh;
    }

So far, the code creates a text layer, places it inside a container, and rotates the container to the position we want our “camera” in. Here we are also setting up the focal point, through the transform-origin property in the .layer class – the 30vh value which means that the focus will be set at 30% the viewport height. Pay attention to the transform-style:preserve-3d property on the .container class as well. That will be necessary since we will be rotating the layers inside the container while keeping its 3D transform. Now let’s see how to clone the layers and create the tilt-shift blur effect. Here we’ll use JavaScript, with a little help from jQuery:

    $(document).ready(function(){
      // how many clones of the text layer we will make
      // the more, the smoother, but it also makes it heavier, so we'll have to strike a balance
      var steps=13; 

      // the total angle difference between the first and the last layers.
      // the bigger, the more pronounced the blur effect will be, but will also require more layers for it to be smooth
      var angle=6;

      // the angle variation between each layer
      var angleDiff=angle/steps;

      // the angle of the first layer
      var startAngle=-angle/2;

      // the opacity of each layer
      var opacityDiff=(1/steps)+0.07;

      var $container=$(".container");

      // the original layer that we will clone and later remove
      var $original=$(".layer");

      // making all the clones
      for(var i=0;i<steps;i++){
          // angle of the current layer
        var a=startAngle+(angleDiff*i);
        var $newLayer=$original
          .clone()
          .appendTo($container)
          .css({
            transform:"rotateX("+a+"deg)",
            opacity:opacityDiff
          }) ;
      }
      // remove the original layer
      $original.remove();
    });

This covers the basics of what we need to get the effect working. Then, we should set the element’s size, position, rotation, color, etc. Here’s a demo of what we’ve made so far, with a few guides to help you understand what is going on.

See the Pen Realistic Text Effect (updated, simple version) by Lucas Bebber (@lbebber) on CodePen.

Getting Fancy

After that, you can tweak the effect to your liking – for instance, adding shading to the text by overlaying it with a gradient, putting a paper texture as background, and so on. I made a few examples to give you an idea.

There are a couple of details in action here: there’s a shading overlay over the text (and the background has a slight shading as well), and there’s a subtle appearance of flipped text behind the main text, to simulate the backside of a somewhat thin paper.

See the Pen Realistic Text Effect (updated, simple version) by Lucas Bebber (@lbebber) on CodePen.

We can also scroll the text and continually change the focus to make an infinite scrolling animation with this effect (currently this demo works best on Chrome).

See the Pen Realistic Text Effect (updated) by Lucas Bebber (@lbebber) on CodePen.

Finally, we can change the focus of the text according to, for example, the mouse’s position. Besides, text is editable in this example: to accomplish that, we set our layers as contenteditable, listen for changes, and update all layers when there’s a change in the text.

And here we’re done:

See the Pen Kinda Realistic Text (with changeable focal center) by Lucas Bebber (@lbebber) on CodePen.

Hope this has been interesting and useful!

Comments (0)
Jun
05

The State of SVG Animation

Posted by: | Comments (0)

The world of SVG (Scalable Vector Graphics) is fascinating, and with everything you can do with it and all the options you have it is overwhelming.

SVG is an XML-based vector image format for two-dimensional graphics, with support for interactivity and animation. In other words, SVGs are XML tags that render shapes and graphics, and these shapes and graphics can be interacted with and animated much like HTML elements can be.

One of the frequently asked questions I get on SVG is about animating SVG images—not only the how, but the what. So let’s have a look at the current (and future) state of animating SVG, and while we’re at it, mention some tips and tools that help you do it painlessly today.

Synchronized Multimedia Integration Language , a.k.a SMIL

Pronounced “smile”, SMIL is an XML-based language that was created to enable authors to write declarative animations to create interactive multimedia presentations. These animations could then be reused to animate other XML-based languages such as HTML and SVG.

In the past as well as the recent present, SMIL has been mostly known in the web community as one of the three ways to animate SVG images.

SMIL comes with a set of animation elements that allow you to animate SVG content. Some of these elements are:

  • <animate> – which allows you to animate scalar attributes and properties over a period of time.
  • <set> – which is a convenient shorthand for animate, which is useful for assigning animation values to non-numeric attributes and properties, such as the visibility property.
  • <animateMotion> – which moves an element along a motion path.
  • <animateColor> – which modifies the color value of particular attributes or properties over time. Note that the element has been deprecated in favour of simply using the animate element to target properties that can take color values.

More elements have then been defined in SVG and more attributes added to extend the functionality of the above elements. The most important animation element defined in SVG was <animateTransform>, which you can use to animate the transformations on an SVG element—such as scale, rotation, skew, etc.

The syntax required to animate an element using SMIL is generally straightforward and human-readable. The attributes—just like the animation elements—are conveniently named so that they are also self-explanatory in most cases.

For example, the syntax to move an SVG element along a certain arbitrary path can look like this:

<animateMotion 
    xlink:href=“#circle”
    dur=“1s”
    begin=“click”
    fill=“freeze”
    path=“M0,0c3.2-3.4,18.4-0.6,23.4-0.6c5.7,0.1,10.8,0.9,16.3,2.3    c13.5,3.5,26.1,9.6,38.5,16.2c12.3,6.5,21.3,16.8,31.9,25.4c10.8,8.7,21,18.3,31.7,26.9c9.3,7.4,20.9,11.5,31.4,16.7 c13.7,6.8,26.8,9.7,41.8,9c21.4-1,40.8-3.7,61.3-10.4c10.9-3.5,18.9-11.3,28.5-17.8c5.4-3.7,10.4-6.7,14.8-11.5
    c1.9-2.1,3.7-5.5,6.5-6.5” />

And for sake of reusability, the above code can be rewritten like this:

<path id=“motionPath” d=“M0,0c3.2-3.4,18.4-0.6,23.4-0.6c5.7,0.1,10.8,0.9,16.3,2.3    c13.5,3.5,26.1,9.6,38.5,16.2c12.3,6.5,21.3,16.8,31.9,25.4c10.8,8.7,21,18.3,31.7,26.9c9.3,7.4,20.9,11.5,31.4,16.7 c13.7,6.8,26.8,9.7,41.8,9c21.4-1,40.8-3.7,61.3-10.4c10.9-3.5,18.9-11.3,28.5-17.8c5.4-3.7,10.4-6.7,14.8-11.5
    c1.9-2.1,3.7-5.5,6.5-6.5”></path> 
<animateMotion xlink:href=“#circle” dur=“1s” begin=“click” fill=“freeze”>
  <mpath xlink:href=“#motionPath” />
</animateMotion>

The difference between the second and first example is that in the second example you separate the path definition and reference it using the <mpath> element; this allows you to reference the same path in multiple <animateMotion> elements, in addition to displaying the path on the canvas, which is what we did in the second example.

The <animateMotion> element in both example could go inside an element that you want to animate, or you can specify the target of the animation using the xlink:href attribute on <animateMotion>.

You can check the live demo for the above example out here.

Motion along arbitrary paths is just one of many examples that can be created using SMIL. These native SVG animation elements can be used to create a diverse range of effects because they allow us to animate practically any animatable attribute in SVG—and this is one of SMIL’s most powerful features.

For example, using the <animate> element, you can animate an element’s color, position, dimensions, and more.

You can also use it to animate path data (the d attribute), thus allowing you to create a shape tweeting effect like the one shown in the image below.

A series of shapes morphine into one another. Image Credit: Noah Blon.

A series of shapes morphine into one another. Image Credit: Noah Blon.

The above example is one created by Noah Blon and is using SMIL to animate the path data from one shape to another. The code in Noah’s example looks like this:

<path fill=“#1EB287”>
    <animate 
             attributeName=“d” 
             dur=“1440ms” 
             repeatCount=“indefinite”
             keyTimes=“0;
                       .0625;
                       .208333333;
                       .3125;
                       .395833333;
                       .645833333;
                       .833333333;
                       1”
             calcMode=“spline” 
             keySplines=“0,0,1,1;
                         .42,0,.58,1;
                         .42,0,1,1;
                         0,0,.58,1;
                         .42,0,.58,1;
                         .42,0,.58,1;
                         .42,0,.58,1”
             values=“M 0,0 
                     C 50,0 50,0 100,0
                     100,50 100,50 100,100
                     50,100 50,100 0,100
                     0,50 0,50 0,0
                     Z;

                     M 0,0 
                     C 50,0 50,0 100,0
                     100,50 100,50 100,100
                     50,100 50,100 0,100
                     0,50 0,50 0,0
                     Z;

                     M 50,0 
                     C 75,25 75,25 100,50 
                     75,75 75,75 50,100
                     25,75 25,75 0,50
                     25,25 25,25 50,0
                     Z;

                     M 25,50 
                     C 37.5,25 37.5,25 50,0 
                     75,50 75,50 100,100
                     50,100 50,100 0,100
                     12.5,75 12.5,75 25,50
                     Z;

                     M 25,50 
                     C 37.5,25 37.5,25 50,0 
                     75,50 75,50 100,100
                     50,100 50,100 0,100
                     12.5,75 12.5,75 25,50
                     Z;

                     M 50,0
                     C 77.6,0 100,22.4 100,50 
                     100,77.6 77.6,100 50,100
                     22.4,100, 0,77.6, 0,50
                     0,22.4, 22.4,0, 50,0
                     Z;
                     
                     M 50,0
                     C 77.6,0 100,22.4 100,50 
                     100,77.6 77.6,100 50,100
                     22.4,100, 0,77.6, 0,50
                     0,22.4, 22.4,0, 50,0
                     Z;
                     
                     M 100,0 
                     C 100,50 100,50 100,100
                     50,100 50,100 0,100
                     0,50 0,50 0,0
                     50,0 50,0 100,0
                     Z;”/>
  </path>

The above code allows you to achieve an effect similar to the one in the following GIF:

tweener

You can have a look at the full code and a live demo here.

What Noah did is specify multiple path shapes inside the values attribute, and then the browser animates between these values—this is possible because these values are numerical and because they are made up of exactly the same number of points; so, practically, it is the point making the path up that are being animated.

The attribute names are almost always self-explanatory, but some of them are not. I have written an extensive article over an CSS-Tricks about SMIL, that contains everything you need to know to get started with it today—should you decide to use it. You can read the article here.

The CSS-Tricks article explains SMIL animation elements and attributes well, but if you want a comparison between SMIL syntax and CSS animation properties syntax that can help you understand SMIL better, you can check out these talk slides from a talk I gave about the topic as well.

SMIL is quite powerful and its performance great, but it was never supported by all browsers. Internet Explorer never supported SMIL—no version of it, and there is currently no intention to do so.

Moreover, SMIL has been intended to be deprecated in Blink (Chrome) as well, in favour of CSS and Web Animations, so the future does not look too bright for these animations.

Deprecating SMIL means losing the ability to animate SVGs embedded as images, without a current alternative. We will talk more about this later in the article.

Animating SVGs with CSS

You can style and animate SVG images using CSS, and animating SVG elements with CSS works almost exactly the same as it does with HTML elements, with the only difference being the type selector names and some property names.

SVG 1.1 did not require any CSS to style SVG elements, so all the styles were applied using presentation attributes. Presentation attribute examples include fill, stroke, stroke-width, opacity, etc.

The following example shows an SVG snippet that uses presentation attributes to style the “border” (stroke) and “background color” (fill) of a star-shaped polygon:

<svg xmlns=“http://www.w3.org/2000/svg” version=“1.1” width=“300px” height=“300px” viewBox=“0 0 300 300”>
  <polygon
fill = “#FF931E”
stroke = “#ED1C24”
stroke-width = “5”
points = “279.1,160.8 195.2,193.3 174.4,280.8   117.6,211.1 27.9,218.3 76.7,142.7 42.1,59.6 129.1,82.7 197.4,24.1 202.3,114 “/>
</svg>

Presentation attributes are a special kind of properties and are used to style SVG elements, and they even contribute to the style cascade in that they override inherited styles on an element, including styles specified in the user agent (e.g. browser) style sheet.

There is a long list of available presentation attributes in SVG. But what we’re interested in is the attributes that can be set and animated via CSS.

Not all presentation attributes can be set in CSS because not all attributes are available as properties in CSS. Only presentation attributes that are available as CSS properties can be set and animated in CSS. A list of all currently available presentation attributes as CSS properties can be found in the SVG 1.1 specification here.

So, if we were to go back to the previous code example and turn the presentation attributes into CSS properties, we can rewrite the code as follows:

<svg xmlns=“http://www.w3.org/2000/svg” version=“1.1” style=“width: 300px; height: 300px;” viewBox=“0 0 300 300”>
<polygon
  style = “fill: #FF931E; stroke: #ED1C24; stroke-width: 5;”
  points = “279.1,160.8 195.2,193.3 174.4,280.8   117.6,211.1 27.9,218.3 76.7,142.7 42.1,59.6 129.1,82.7 197.4,24.1 202.3,114 “/>
</svg>

The styles can also be moved out into their own <style> “island”, just like HTML styles can be. Now, in the above example, if the width and height were set on a <rect> element inside the SVG, we wouldn’t have been able to set those attributes in CSS on the <rect> element because it’s still not possible.

In the new SVG 2 specification, the list of SVG styling properties is extended to include more properties such as content size and geometry properties including—but not limited to—x, y, width, height, cx, cy, r, and more. The new list can be found in the SVG 2 specification here.

Note that some of these properties are already available in Chrome, so you can test them in that browser if you want.

It only makes sense that if some properties can be set in CSS and their values are animatable then the properties can also be animated in CSS, and thus the SVG elements these properties are applied to can also be animated via CSS…

CSS Transitions and Animations on SVG Elements

Indeed, you can apply CSS animations and transitions to the animatable SVG properties in CSS. This allows you to create nice hover interactions such as changing the fill color of an icon, for example, and more complex animations such as transformations in both the second and third dimensions.

For example, to change the fill color of an SVG icon on hover using CSS, you would do it just as you might expect, like so:

.icon—twitter {
    fill: #eee;
}
.icon—twitter:hover {
    fill: #55ACEE;
}

As a matter of fact, CSS is perfect for simple animations and interactions like hover interactions, and it also generally performs very well, though not in all browsers, since CSS animations on SVG elements are currently not hard-ware accelerated in all browsers, so performance can be better—and hopefully will improve in the future.

Moreover, note that CSS animations (using @keyframe, for example) do not work in IE9 and below.

CSS Transforms on SVG Elements

The most impressive kinds of effects usually include some kind of transformation animation that either rotates, scales, skews, or simply translates an element. A simple example using transformation animations is the following set of weather icons also created by Noah Blon and available on Codepen.

See the Pen SVG Icons Animated with CSS by Noah Blon (@noahblon) on CodePen.

Some of the icons translate a group of shapes (e.g. the rain drops) from their initial position “in the cloud” downwards, infinitely, others use a rotation transformation to rotate the sun about itself, etc.

Now, if you are viewing the above demo in Firefox, you will notice that some of the animations are broken. There is a reason for that.

Animating SVG elements using CSS is very similar to animating HTML elements with CSS, with one major difference when it comes to transformations: by default, the initial default transform origin of an HTML element is (50%, 50%), which is the element’s center. By contrast, an SVG element’s transform origin is positioned at the origin of the current user coordinate system, which is the (0, 0) point in the top-left corner of the canvas.

So, suppose we have an HTML <div> and an SVG <rect> element:

<!DOCTYPE html>
…
<div style=“width: 100px; height: 100px; background-color: orange”> </div>
<svg style=“width: 150px; height: 150px; background-color: #eee”>
  <rect width=“100” height=“100” x=“25” y=“25” fill=“orange” />
</svg>

If were were to rotate both of them by 45 degrees, without changing the default transform origin, we would get the following result (the red circle indicates the position of the transform origin):

initial-to

So, if you want to animate an SVG element around its own center, you need to explicitly set the transform origin using the transform-origin property.

rect {
  transform-origin: 50% 50%;
}

Changing the transform origin on the SVG element like that would give you the following result:

set-to

That being said, this does not currently work in Firefox. It is a known bug.

Noah’s demo uses percentage values to set the transform origin to be the center of the animated elements, and this is why it is broken in Firefox. The way to make a rotation work in Firefox as you would expect it to is to use absolute values (pixels, ems, etc.) to set the transform origin. And when you do that, the origin will be specified relative to the SVG canvas’ user current coordinate system. For example, if you specify 50px 50px as a transform origin, it will be the point at 50px 50px from the top left corner of the SVG, not relative to the element itself.

In most cases, this is not how you want to set a transform origin, but it is necessary at the time being to make it work in Firefox.

In addition to the problem in Firefox, IE and Opera have a problem which is that they do not honor CSS transforms at all on SVG elements. And there are quite a few more issues that we will mention in a later section in the article.

Much more complex animation effects can be created by animating SVG using CSS, but these effects mostly rely on transformations to look great, and CSS transformations are currently limited, buggy and inconsistent across browsers.

However, you can do more with CSS than simply transition colors or transform elements…

SVG Line Drawing Effect with CSS

One of the most impressive and popular SVG animation effects is the line drawing effect. An example of the line drawing effect was first seen on the Xbox website and is explained in this article on the Vox media blog. The animation can be seen in the following recording:

xbox

This effect is created by animating two specific SVG properties—namely stroke-dasharray and stroke-dashoffset. The first property allows you to turn your solid line “border” (stroke) into a dashed line, by specifying the length of the dashes and spaces in between them, and the second property allows you to change the offset—that is, the position at which these dashes start along the path’s line length. Both of these properties are available in CSS and are animatable.

By turning the path you have at hand into one long dash and then animating the offset of that dash along the path, you can mimic a line drawing effect using nothing but CSS and an SVG path.

This effect was first explained by Jake Archibald in this article over on his blog. The article also included an interactive demo that explained how this technique works. The following is a recording using that demo to show the effect of the two properties:

line-drawing-demo

You can play with the demo yourself in Jake’s article.

The trick behind this technique is to know the exact length of the path so you can turn it into one dash of that same length, and then use that same length as an offset value to “pull” the dash outside the visible boundaries of the path (backwards), and then animate it back in.

The formula to create this effect in CSS thus looks like so:

#path {
    stroke-dasharray: pathLength;
    stroke-dashoffset: pathLength;
    /* transition stroke-dashoffset */
    transition: stroke-dashoffset 2s linear;
}

svg:hover #path{
    stroke-dashoffset: 0;
}

This line drawing effect is very effective in creating more expressive UI elements. You can see a whole lot of examples using this technique to improve common UI elements and interactions on Codrops. A couple of examples are:

Now, in a lot of cases, you may not know the exact length of the path you want to animate, and if you have many paths you’re animating, it can become tedious to know and then set and animate the length for each one. This is where a JavaScript solution is a better option.

In fact, JavaScript enables you to overcome many of CSS and SMIL’s animation limitations, especially when it comes to animation timing and synchronization capabilities…

Animating SVGs with JavaScript

Using JavaScript to animate SVGs, you get the same capabilities you would get with SMIL and CSS, and more. There is only one limitation I can think of when you use JS to animate SVGs—we will talk more about that in the next section.

If we were to get back to the last example in the previous section where we created the line drawing animation using CSS, we can do the same thing using JavaScript, and thanks to the SVG DOM method getTotalLength(), we can always know the length of the path we’re working on by simply selecting that path and using this method to retrieve that value:

var path = document.querySelector(‘.drawing-path’);
path.getTotalLength();
//set CSS properties up
path.style.strokeDasharray = length;
path.style.strokeDashoffset = length;
//set transition up
path.style.transition = ‘stroke-dashoffset 2s ease-in-out’;
// animate
path.style.strokeDashoffset = ‘0’;

In most cases, and unless the animation is very simple, you will want to use JavaScript to create this effect. Some plugins that help you do this already exist—example here and here; the latter is a plugin for the very popular animation library: Greensock.

If you animate SVGs using vanilla JavaScript from scratch, you will still face some of the browser inconsistencies and bugs mentioned earlier. Some of the available SVG animation libraries can help you avoid that because they take care of all of this for you.

There are many SVG animation libraries out there; the three most popular ones are: Greensock, Snap.svg and Velocity.js. I’m sure that if you work with SVG animations, you can think of a couple more (for example, D3.js), but these are the three most popular ones today.

Using JavaScript, you can animate SVG path data (d attribute) too. This allows you to create some really impressive animations that can literally take your animations and UIs to the next level.

For example, the following recording shows an effect created by Codrops’s Manoela Ilic, which recreates Mac OS X’s genie effect by animating the shape of a path (the lime green area):

genie-sm

Even more creative effects can be created that can improve upon the general user experience of a user interface by leveraging proper animation effects to help hint the user on the whereabouts of elements, in addition to creating more realistic interface effects.

You can also use JavaScript to create simple transitions and animations that you can do in CSS, but without the browser bugs. Greensock, for example, provides you with a cross-browser way to do so, because it takes care of providing the appropriate technique to create those animations in Internet Explorer, for example, by falling back to SVG attribute animations instead of CSS property animations which are not supported in IE.

The Web Animations API—a JavaScript animation API—is meant to fill in the gap for some (if not all) of the functionality that SMIL provided—and that is fantastic, but it still will be limited in the case where the SVG is embedded as an image. Read along for details.

SMIL vs CSS vs JavaScript

The current and future state of browser support for SMIL is the main reason why I neither use it nor recommend using it anymore today. Unless the state of support changes so that more browsers support is, not less, then I don’t see this changing any time soon, and I expect SMIL usage to drop even more in the future.

As for CSS, it can only animate so many SVG properties, not all of them. Attributes such as the data attribute d of a path cannot be animated in CSS—at least not yet. So no shape tweeting effects can be established using CSS at the time being, or any other path animation effects for the matter.

Not to mention that Internet Explorer up to version 11 did not support CSS animations and transitions on SVG elements, and the new MS Edge browser still does not support CSS transformations on SVG elements. All this and the transform origin bug in Firefox along with a lot of browser inconsistencies when animating SVG with CSS are a reason why I only recommend using CSS for simple, possibly trivial animations that are not vital to the functionality of whatever you’re working on. If the animation is crucial to the image, page or application, I certainly recommend using JavaScript.

Note: Jack Doyle wrote an extensive article on CSS-Tricks explaining the browser bugs and inconsistencies when it comes to applying CSS transformations to SVG elements. You can read the article here.

All that being said, CSS is already getting more capabilities that spawn from SVG SMIL animations. Today, we have a CSS Motion Path Module which imports SMIL’s motion along a path capability into CSS, so we can animate SVG and HTML elements along paths using nothing but CSS. The Web Animations API previously included this functionality, but it was later on removed with the introduction of the CSS Motion Path Module.

However, with SMIL being deprecated, CSS is going to need more than the motion path module to fill in the gaps, because we still can’t animate SVG paths in CSS, and CSS also does not let you sequence and group animations so they play perfectly together. SMIL’s animation triggering and synchronisation capabilities are superb, and CSS still comes short in this aspect.

This is why JavaScript is currently my go-to tool for animating SVG, and my library of choice is Greensock. Greensock has a lot of features that focus on SVG animations, and allow you to write and create SVG animations without having to worry about browser inconsistencies. Greensock also adds more to the animation methods and properties so you can create animations that behave just as you would expect them to, by working around some non-intuitive default animation behaviour in SVG.

Snap.svg is the go-to library for SVG manipulation and is known as the jQuery is SVG, but Greensock’s timeline feature and other features it has makes it more powerful when it comes to creating complex SVG animations.

That being said, JS comes with one major limitation when animating SVG: an SVG embedded as an image—using <img>, <picture> or a CSS background image—cannot be animated using JavaScript, for security reasons.

What does this mean? It means that if your SVG is embedded as an image, any JavaScript animations you define on it will not work. Only CSS and SMIL animations work, and the former need to be defined inside of the <svg>, not externally. Interactions (such as :hover) will not work either way.

SMIL allows us to create complex path animations and have them work in SVGs embedded as images; but SMIL is going to be deprecated, and CSS does not yet have this ability, so we need to wait till CSS gets more features to fill in SMIL’s shoes; until then, animating an SVG as an image will be very limited.

Mozilla’s Brian Birtles has written an article where he discusses the most common use cases of SMIL, and lists some features that CSS needs to getting order to fill in the gap created by SMIL’s deprecation. But until then, you can either use SMIL and drop support for IE and Chrome in your images, or simply settle for simple animations using CSS, or use JavaScript to create awesome effects and embed your SVG in one of the other possible embedding techniques.

In addition to what each animation technique can or cannot do, you can read more about how each of them performs in this excellent article by Sarah Drasner, where she weighs the different animation techniques with benchmarks, comparing CSS, SMIL and a couple of JavaScript animation libraries. Make sure you check the article out for details.

Final Words

SVG is a big world, with a lot of options and a lot of developments and changes happening on an almost daily basis. You need to weigh your options and your needs, and pick the technique that works best for you—from the creation stage, to optimization, to embedding and finally animation. I hope this article helped give you an overview of what’s currently possible and not possible in the world of SVG animation, hopefully making it easier for you to choose the appropriate animation technique for your next project. I certainly did not cover every aspect of this topic, but hopefully enough to help you make a better choice when choosing an SVG animation tool today.

Thank you for reading. :)

Comments (0)

Over the past couple of years, CSS has gotten a set of new properties that allow us to create quite advanced graphical effects right in the browsers, using a few lines of code, and without having to resort to graphics editors to achieve those effects. If you are like me, then that sounds like music to your ears. I don’t do well in graphics editors and would choose a code path over a graphical editor path any day. CSS now allows us to do more graphical work right in our text editors.

Examples of graphical effects that we can create using CSS today include textured text effects, photo effects like color editing/tweaking, photo and element blending that also enable us to blend elements with other elements, clipping content to arbitrary shapes, and more. You can even wrap content to arbitrary shapes with CSS too!

CSS has gone a long way, and in this article I want to give you an overview of the CSS features that allow us to create such graphical effects—namely blend modes and filter effects.

Color Blending with CSS Blend Modes

If you’re a designer who frequently fires up a graphics editor such as Photoshop or Illustrator, then you’ve inevitably come across blending modes at some point or the other during your work, since blending is one of the most frequently used effects in graphic and print design. Blending operations, also known as blend modes provide us with a fine level of color blending control that enables us to perform operations such as inverting colours, mixing them, highlighting them, and more.

Different blend modes, when used, yield different effects. And a blend mode is used to specify how an element, known as the “source” will blend with its backdrop—also known as the “destination”.

In CSS, the element’s backdrop is the content behind the element and is what the element is composited with. Compositing is the fancy term for the process of combining an graphic element with its backdrop.

When you blend two elements in CSS with each other, only the areas where these elements overlap will be affected by the blend mode you choose because, as you can imagine, only those areas are where these two elements can be blended.

Before the CSS Compositing and Blending specification was introduced, CSS already offered us one way of compositing elements known as simple alpha compositing. This is what the opacity property is for. By changing an element’s opacity, the browser makes it translucent so that the colours of its backdrop can show through.

Today, two main properties exist in the CSS compositing and blending specification that enable us to blend elements with other elements and an element’s background images by specifying one of 16 available blend modes. These two properties are: background-blend-mode and mix-blend-mode.

Blending Background Images Using The background-blend-mode Property

The background-blend-mode property, as its name suggests, is used to specify a blend mode for an element’s background layer. A background layer can be an image, or the background color.

The background-blend-mode property is used to specify the blend mode for each background layer.

If the element has more than one background image, you can specify multiple blend modes—each blend mode will be used for a background image such that the first blend mode in the list corresponds to the first background image in the list of background images, and so on.

For example:

background-image: url(first-image.png), url(second-image.png);
background-color: orange;
background-blend-mode: screen, multiply;

The second-image.png background will blend with the background color using the multiply mode, and then the first-image.png background will blend with the second image and the background color using the screen blend mode. (Reminder: the first background image in the list is the one on top, and the ones following it are beneath it.)

The background images will only blend with each other—they will not blend with any content that lies underneath the element itself.

There are 16 blend modes available in CSS: normal (which is the default blend mode and means that no blending is applied), multiply, screen, overlay, darken, lighten, color-dodge, color-burn, hard-light, soft-light, difference, exclusion, hue, saturation, color and luminosity. (For the sake of brevity, I will refrain from going into technical detail about each of these modes, and will recommend this article instead to learn all about them.)

These blend modes will modify the colours of a background image resulting in a different effect for each mode.

The hardest part comes when picking a blend mode to achieve a specific effect is knowing which mode to pick. It is very hard—if not impossible—to predict the result of applying a certain blend mode to an image.

The following image shows a set of results achieved when applying the above mentioned blend modes to an image. The image is being blended with a red background color. The order of blending operations from the top left corner of the image is the same as the order mentioned in the list above.

background-blend-mode-examples

The result of applying the different blend modes to an image, in the same order mentioned above, starting from the top left corner.

Usually, the way to choose a blend mode is by trial and error. Apply the blend modes to your image and settle for the one that achieves the effect you’re after.

Some blend modes, however, yield expected results and you can memorise those and use them whenever you need. For example, the luminosity mode allows you to create monotone images (bottom right corner)—this is a handy tip to keep in mind for when you’re after creating that big header image with a white heading on top which became very trendy during the past year.

As part of an article I wrote a while back, I created an interactive demo which allows you to upload your own image and preview the different blend modes on it. You can play with the demo here.

Screenshot of the interactive blend modes demo.

Screenshot of the interactive blend modes demo.

Blending background images is great and you can achieve some really neat effects using this property. The following image shows an example of blending an element’s background image with a linear gradient image also used as a second background image on the element. This image is taken from this live demo from the Codrops CSS Reference.

The result of blending a linear gradient background image with a photo background image on an element.

The result of blending a linear gradient background image with a photo background image on an element.

More creative effects can be created when you get to blend an element with other elements on the page. This is useful for when the images you’re blending need to be foreground images—not background images, and when you want to blend a piece of text, for example, with the image behind it. This is where the mix-blend-mode property comes in.

Blending Elements with Their Backdrop using mix-blend-mode

Probably one of the most useful and practical use cases for mixing elements is mixing a piece of text with some image behind it. And this is where the interesting effects come in. Think fixed headers blending with the content as the page scrolls down, or text blended with an image in the background, or text blending with other text, etc. Using the mix-blend-mode property you can do exactly that.

Just like background-blend-mode, the property accepts one of the 16 blend mode values available. Again, to see this in action, you can refer to the interactive demo mentioned earlier.

The following screen recording shows how you can add a piece of text and then blend it with an image of your choice using one of the different blend modes.

mix-demo

Screenshot of the interactive demo showing the mix-blend-mode property in action.

An example blending a piece of text with a background image behind it could look like the following. Assuming the piece of text is contained in a wrapper that has a background image applied to it, we could have something like:

<div class=“wrapper”>
    <h1>This is a blended heading</h1>
</div>
.wrapper {
     background-image: url(path/to/image.jpg);
   background-size: cover;
    /* … */
}
h1 {
    mix-blend-mode: multiply;
     /* other styles here */
}

You can also blend text with other text, allowing you to achieve nice colourful text overlapping effects like the one shown in the top right corner of the following image. All of the effects shown in this image can be achieved using different CSS blend modes.

blending-examples

Examples of effects created using CSS blend modes.

Using negative margins or relative positioning, you can shift the position of one word so that it overlaps with the word next to it, and then apply a mix-blend-mode to the word to blend it with the other word. The possibilities are endless.

Blending Notes

Sometimes, you may not want to blend an image or an element with its backdrop, or you only want to blend a group of elements together but prevent these elements from blending with other content behind them. This is where stacking contexts come in play and, using a property called isolation, you can isolate a group of elements so that they only blend with each other and don’t blend with other content on the page.

By creating a stacking context on an element, you can isolate the content of that element and prevent them from blending with the backdrop of that element. However, you can still apply a blend mode to the entire context to blend it with its backdrop.

Moreover, If you are using the background-blend-mode property, the isolation property is not needed since background layers must not blend with the content that is behind the element, instead they must act as if they are rendered into an isolated group (the element itself), as specified in the specification. This is why the isolation property will have an effect when used with the mix-blend-mode property, but not with the background-blend-mode property.

You can learn more about the isolation property here.

Note that the mix-blend-mode property also allows you to mix or blend SVG elements too.

Browser Support

CSS blend modes support is getting better by the day. You can keep an eye on browser compatibility for the background-blend-mode property here; support for mix-blend-mode can be found here.

Whether or not a property has full browser support, you can always start using it as part of a progressively enhancing workflow. These blend modes can be used to enhance your page designs, while falling back to non-blended alternatives in non-supporting browsers. By using a feature today, you’ll help push it forward and your design will eventually look right in other browsers as they support these features. So don’t let a limited browser support stop you from having fun with these properties today!

Image Adjustments with CSS Filter Effects

A filter effect is a graphical operation that is applied to an image as it is drawn into the document. It can be described as an operation that passes an image through a filter and then renders the output of that image on the screen.

One way to think of them is like a filter placed on the front of a camera lens. What you’re seeing through the lens is the outside world modified by the effect of the filter. What you see on the screen is the content modified by the filters applied to it.

To apply a filter to an image using CSS, you use the filter property defined in the CSS Filter Effects specification.

Filter effects include, for example, blur effects, drop shadows, and colour shifting and manipulation like saturating/desaturating colours, among others.

There are ten primitive filter effects in CSS, and a filter is applied to an element by passing a filter function to the filter property.

The ten filter functions are:

▪ blur()
▪ brightness()
▪ contrast()
▪ grayscale()
▪ hue-rotate()
▪ invert()
▪ opacity()
▪ saturate()
▪ sepia()
▪ drop-shadow()
▪ url()

Each of these functions is used to manipulate the image’s pixels and colours, and each function takes a parameter value that specifies the degree or intensity of the filter applied.

Conceptually, any parts of the element are effected by filter operations. This includes any content, background, borders, text decoration, outline and visible scrolling mechanism of the element to which the filter is applied, and those of its descendants.

The blur() function

The blur() function is used to blur an element by applying a Gaussian Blur to that element. It takes a length value as a parameter; this value needs to be a positive number and cannot be set in percentages. The larger the value the more blurred the element will be. A value of zero will leave the element unchanged.

What’s interesting is that since the parameter of the blur() function is a length value, this means that you can use any possible length unit, like em and rem.

The following are examples of valid blur() values:

blur(.5em);
blur(7px);
blur(0);
filter: blur(); /* equivalent to blur(0); */

The following image shows the result of applying a 10px blur to an image:

blur

The brightness() function

The brightness() function is used to manipulate the image brightness. It is used to make the image look more or less bright. It adjusts an image’s colours between completely black (zero brightness) and the original image colours (100% brightness). A value of zero will render the image completely black. A value more than 100% will increase the image brightness.

You can also specify the amount of brightness using a number instead of a percentage such that a percentage value of 65%, for example, would be expressed as 0.65 instead.

For example, the following are all valid brightness() values:

brightness(150%);
brightness(0);
brightness(0.7);
brightness(0.01);
brightness(200%);
brightness(10%);

The following image shows the result of applying a 200% brightness to an image:

brightness

The result of applying a 200% brightness to an image.

The contrast() function

The contrast() function adjusts the contrast of the image. That is, it adjusts the difference between the darkest and lightest parts of the image.

The function is similar to the brightness() function in that, just like brightness(), a value of zero will render an image completely black. As the value increases towards 100%, the difference in darkness changes until you see the original image at 100%. Values beyond 100% will increase the difference between light and dark areas even more. If no value is passed to the contrast() function, it defaults to 100% and the image is not changed.

contrast() also takes the same values as brightness(), so the following are all valid examples:

contrast(150%);
contrast(0);
contrast(0.7);
contrast(0.01);
contrast(200%);
contrast(10%);

And the following image shows the result of applying a 200% contrast to an image:

contrast

The result of applying a 200% contrast to an image. (That is one angry cat there! ;))

The grayscale() function

The grayscale() function converts the image into a shade of grey.

The value is also a percentage or a decimal number equivalent to that percentage. However, the percentage values need be between 0 and 100%. Any value greater than 100% will be clamped to 100%. 0% leaves the image unchanged while 100% makes it completely grey. The higher you go from zero to 100% the more the image loses its colours and becomes grey.

The following are all examples of valid greyscale() values:

filter: grayscale(); /* defaults to grayscale(100%) */
filter: grayscale(1); /* same as grayscale(100%) */
filter: grayscale(36%);
filter: grayscale(0.28);

The following image shows the result of applying a 100% grayscale to an image:

grayscale

The result of applying a 100% grayscale to an image.

The hue-rotate() function

The hue-rotate() filter function rotates the colours of an image by an angle that is to be passed to the function as a parameter.

A simpler way to understand this would be to imagine a color wheel. Every color on the color wheel has an angle at which it is positioned. If you start at one point (color) at the circle and then move along the circle by a certain angle, you end up at another point with another color.

What the hue-rotate() function does is it selects each color of the input image, rotates it by the angle value passed to it, and then outputs the image with the input colors replaced with new colors. All the colors in the image are shifted in the same way to produce new colors.

A value of zero renders the image unchanged. The maximum angle of rotation is 360 degrees. If the value for the angle is not provided, it defaults to the value 0deg and the image is not changed.

The following image shows the result of applying a 120deg hue rotation to an image:

hue-rotate

The result of applying a 120deg hue rotation to an image.

The invert() function

The invert() function inverts the colours of an image. It takes a value between 0 and 100% such that the higher you go from zero to 100% the more the image will look inverted. A value of 100% is completely inverted—all the colours are flipped so that the image looks like a photo negative (like the ones generated for old non-digital cameras). Any value over 100% will be clamped back to 100%. A value of 0% leaves the input unchanged.

Note that if you don’t pass a value to the invert() function, it defaults to 100% and the image is completely inverted. And the percentage values can also be represented as decimal numbers as well.

The following are examples of valid invert() values:

invert(); /* equivalent to invert(100%) */
invert(0.24);
invert(60%);

The following image shows the result of inverting an image’s colours completely using a 100% default value:

invert

The result of inverting an image’s colours completely using a 100% default value.

The opacity() function

The opacity() function is similar in functionality to the CSS opacity property. It accepts values between 0 and 1 or its equivalent 100%. 100% means the image or element is fully opaque, and as you go down from 100% to zero, the element becomes more and more translucent until it becomes completely transparent at zero, and then the content on the page that lies behind it—if any—will show through it. Even if you pass in a value greater than 1, the browser will clamp it down to 1/100%. Negative values are not allowed.

The following image shows the result of applying a 0.5 opacity value to an image:

opacity

The result of applying a 120deg hue rotation to an image.

The saturate() function

The saturate() function saturates the colours of the image making it look more vivid. It takes a value between zero and 100% or the value’s equivalent decimal number. A value of 100% leaves the image’s colours unchanged. The value of zero completely desaturates the image while a higher value saturates the image more, and values greater than 100% will super-saturate the image. Negative values are also not allowed.

Saturating images is particularly useful for when the image’s colours are looking dull and you want to give them a more lively appearance.

The following example shows the result of applying a 250% saturation value to an image:

saturation

The result of applying a 250% saturation value to an image.

The sepia() function

Ever heard of “the sepia effect”? You likely have—ißßt’s that effect that gives a vintage appearance to an image. The sepia() function gets its name from the fact that it adjusts an image by giving it a sepia tinge like in old photographs.

Just like previous functions, it takes a value (percentage or decimal) between 0 and 100%. The higher you go from zero the stronger the sepia effect. Values greater than 100% will be clamped to 100%.

The following is the result of applying a 100% sepia tone to an image:

sepia

The result of applying a 100% sepia tone to an image.

The drop-shadow() function

The box-shadow CSS property allows us to apply a box shadow to an element. This means that even if you have a non-rectangular element or a non-rectangular image (like a PNG), the shadow applied to that element is going to be rectangular as if the element is a rectangular box. This, in many scenarios, is an unwanted results.

For example, suppose you have the following PNG image of a star. Since it’s a PNG, it is made up of some fully transparent areas, and the star is the only opaque area. When you want to apply a drop shadow to the image, you’ll likely want to achieve the following result:

drop-shadow

An image with a drop shadow applied.

Using box-shadow, you’d end up with something like this instead:

box-shadow

An image with a box shadow applied.

This looks ugly.

The drop-shadow() filter function allows us to achieve the previous result.

The drop-shadow() function takes a value similar to the value accepted by the box-shadow property, except that the drop-shadow() function’s shadow does not include a spread radius like the box-shadow‘s does, and the inset keyword is also not allowed in the drop-shadow() function. I’ll assume you’re familiar with the values of the box-shadow property. If not, please refer to this entry in the Codrops CSS Reference for a list of possible values and detailed explanation and examples of each.

To apply a drop shadow using drop-shadow(), you pass in the value of the shadow you want and simply apply it to your image. For example:

.png-img {
    filter: drop-shadow(10px 10px 3px rgba(0,0,0,0.3));
}

The url() function

The url() function allows you to use a filter defined in an SVG document and apply it to your element. Instead of using one of the above 10 filters, you can define your own filter in SVG and then apply it to the element by referencing the filter’s ID in the url() function. For example:

/* filter from an external SVG file */
filter: url(myFilters.xml#effect);
/* or filter defined in the main page */
url(#myFilter);

The following is an example of a blur filter defined in SVG:

<svg height="0" xmlns="http://www.w3.org/2000/svg">
  <filter id="myFilter" x="-5%" y="-5%" width="110%" height="110%">
    <feGaussianBlur in="SourceGraphic" stdDeviation="8"/>
  </filter>
</svg>

Referencing that filter in CSS and applying it to an element would apply a Gaussian blur filter to that element.

Since SVG filters are a big and wide topic, we won’t be getting into the details of them in this article.

Live Demo!

Because CSS Filters are not supported in all browsers, I showed screenshots of the effects in all of the previous examples. That being said, you can still play with the filter values in the following live demo:

See the Pen 7405c808441c8021bb6bc59baef72441 by Sara Soueidan (@SaraSoueidan) on CodePen.

Just like with CSS blend modes, you can use CSS filters to enhance your pages, so you don’t need to wait for full browser support to start playing with and taking advantage of this cool CSS feature.  

Multiple filters

You can apply multiple filters to an image or element. When you apply multiple filters to an element, the order in which you apply those filters matters and changes the final output of that element. If you apply multiple filters, these filters should be space-separated. For example:

filter: sepia(1) brightness(150%) contrast(0.5);

 

Animating filters

Filters can also be animated, this allows you to create some really creative effects. An example of multiple filters being animated on an image is the following image fading effect by Lucas Bebber:  

See the Pen Pretty Fade by Lucas Bebber (@lbebber) on CodePen.

Lucas’s work is extraordinary, so you might want to check his Codepen profile out for more beautiful experiments that are sure to spark your creativity.. and curiosity.

Order Of Graphical Operations

In addition to blending and filters, an element could also be clipped and/or masked. If you apply more than one graphical operation to an element, the browser needs to decide which operation to apply first, and depending on the order, the end result would be different.

There is one specified order of operations in CSS according to the specification: first any filter effect is applied, then any clipping, masking, blending and compositing.

Inspiration

Not long ago, Dudley Storey created a neat experiment using CSS blend modes and clipping paths to create a 3D Glasses effect.

3d-glasses

Screenshot of Dudley’s 3D Glasses demo using CSS blend modes.

You can check his demo and tutorial out here.

Final Words

CSS Blend Modes and Filters are only two of the features that CSS proves us with to create graphical effects on the web. Other effects also exist that bridge the gap between print design and web design, giving us—web developers and designers—more control and better tools for designing in the browser, without having to resort to graphics editors to achieve such simple—yet powerful and impressive—effects.

If you’d like to learn more about other CSS graphics features, make sure to leave a comment below requesting a followup article.

I hope you found this article useful. Thank you for reading!

Comments (0)

Creating an image carousel (slideshow) using HTML, CSS and Javascript is a challenging task that only advanced web designers and developers can accomplish, right? Wrong! In this Your Questions Answered post, we’ll be walking you through how to build a responsive carousel in Dreamweaver CC using the Bootstrap Carousel Plugin from w3school.com.

Unless you have been living under a rock for the past couple years, you’ve probably heard of the term responsive web design and you likely know what it is. However, in case you’re not sure it’s a technique for building websites that dynamically adapt to any screen or device based on the size, resolution and orientation.

Bootstrap is a HTML, CSS and JS framework for developing responsive, mobile first projects on the web.

Building a Responsive HTML Carousel Using Bootstrap

To get started:

  1. Launch Dreamweaver CC.
  2. Select Site > New Site.
  3. In the dialog box that appears, enter the following information:
    1. Site Name
    2. Local Site Folder: Click the Browse or Folder icon. Navigate to any of your local folders you want to use for this project.
    3. Click Save
  4. Create an image folder under the Site you just created and call it “img”.
  5. Copy your images to this folder.
  6. Select File > New.
  7. Select Blank Page, page type as HTML, and Layout as none.
  8. Save the page as slideshow.html.
  9. Open this page in your web browser.
  10. Copy the contents below Edit This Code.
  11. In Dreamweaver, select the content in Code view and paste the content that you copied.
  12. In the HTML section of the code, edit the <img> tag to read <img src=”img/<nameofimage.jpg>”> For instance, for the first image, I used <img src=”img/img_chania.jpg”>
  13. I have edited the H3 Tag and the P tags to add the relevant captions for the images. You could do that as well.
  14. Select File > Preview in Browser to preview in a browser of your choice.

Resize the browser window. The images and captions in the slideshow should resize to fit the new dimensions of the screen.

Tell me more

If you look in the <head> section of your code, you should see the following:

<meta name="viewport" content="width=device-width, initial-scale=1">

  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

  <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>

What is happening here is that the page is linked to CSS and JS files at remote locations. Dreamweaver gets the contents of these files and displays them for you. Because the files are at a remote location, you cannot edit them in Dreamweaver.

Feel free to click on each of the files to look at the code contained in each of them.

For a list of websites and applications built using Bootstrap, see http://bit.ly/1F1QArx.

Comments (0)

Applying background images to elements is probably one of the most used features in CSS, and many background properties exist that allow us to control different aspects of an element’s background.

An element can have more than one background image. If you want to apply more than one background image, you can provide them as a comma-separated list of values for the background-image property. The background-position property is used to specify the position of the background image, and this property is worth a deeper look because its different possible values have different results, some of which might be new to you if you are not very deep into CSS.

To keep the code and concepts throughout this article simple, we’ll be positioning one background image throughout the examples. But what applies to one background image applies to multiple images as well.


A background image is positioned inside what is called a background positioning area of an element. This background positioning area,as the name suggests, specifies the area inside which the background will be positioned, and has a coordinate system used to handle the positioning.

Before we dig into the concepts of positioning further, let’s first have a quick look at the CSS box model and see how it affects the positioning of background images inside an element.

The CSS Box Model Areas

An element in CSS has three areas, called boxes, defined on it: the border box, the padding box, and the content box. The border box is the area of the element that includes its entire innards plus the area underneath its border.

The padding box is the area of the element that excludes the border and includes the element’s content and the surrounding padding — specified using the padding property.

The content box is the area created by the element’s content, excluding any padding and border.

box-areas

An element’s box areas. Image Credit: The Codrops CSS Reference, background-origin entry.

There’s also a fourth area called the margin box which includes the element and its outer margin that you specify using the margin property.

When you give an element a background—be it an image or a solid color—that background is painted across the element’s padding area by default. (This behaviour can be modified using the background-origin property, but we’ll get to this shortly.)

In order to specify where exactly the background image will go inside the positioning area, this area needs a coordinate system used to translate the position values into. Let’s take a closer look at this coordinate system before we move forward.

An Element’s Coordinate System

By default, and due to the nature of an element’s box model in CSS, every element has a coordinate system established by its height and width. This coordinate system is used to position the element relative to other elements, and to position the element’s descendants relative to the element itself.

An HTML element has a coordinate system in CSS. SVG elements, on the other hand, don’t have a similar coordinate system because they are not governed by the concept of the box model.

The origin of the coordinate system in CSS is located at the top left corner of the element.

A background positioning area is also governed by a coordinate system established on that area, and is used to position the background image in that area. This coordinate system also has its origin at the top left corner of the positioning area.

Since the default positioning area is the padding box, then, by default, the origin of the background positioning area’s coordinate system is the top left corner of the padding box.

This means that when you apply a background image to an element, the browser will position the first and subsequent repetitions of the image starting from the top left corner of the padding area.

For example, suppose you have a background image applied to an element and you do not set that background image to repeat (so only one instance of that image is applied). The initial position of the background image inside the coordinate system is at the origin of the padding box’s coordinate system. So, the top left corner of the image is positioned at the top left corner of the padding box. (See live example below.)

See the Pen Adobe background-position by Sara Soueidan (@SaraSoueidan) on CodePen.

Using the background-position property we’ll talk about in this article, we can then change the position of the image inside that coordinate system.

But as we mentioned before, we can change the background positioning area and this, in turn, will change the origin used to position the image inside the element’s background area.

 

Changing The Background Positioning Area & Coordinate System Using background-origin

The background-origin property is used to change the origin of the coordinate system used to position the background image in the background positioning area.

It takes one of three values: padding-box (which is the default value, content-box and border-box.

Depending on the background positioning area you choose, the corresponding background origin — the origin of the coordinate system established on that area — will change, and so will the initial and default position of the background image.

The following live example shows the different background origin / positioning areas in action.

See the Pen Adobe background-origin — different values by Sara Soueidan (@SaraSoueidan) on CodePen.

For each background positioning area specified using background-origin, the coordinate system will “shift” to cover that area.

Then, we can specify the position of the background image in that coordinate system using the background-position property.

For the sake of simplicity, we will not be changing the default background positioning area of the element in the rest of this article. So all of our examples will be applied to an element whose padding area is the area inside which the background is positioned.

Positioning Background Images Using background-position

We saw in the previous section how the background image is positioned by default at the top left corner of the positioning area. This is due to the fact that the default position value for the background-position property is 0% 0%.

The default position is a percentage value. You can supply background-position with either a percentage value or an absolute value, that specify the offset of the image from one of the positioning area’s four edges (top, right, bottom, left).

offset-edges-and-system

An element’s offset edges and coordinate system in CSS.

In addition to percentage and absolute offset values, five offset keywords exist and can be used: top, right, bottom, left and center.

A position can be described by specifying one offset value (keyword, percentage, or length), two offset values (a combination of two of the three possible values), or four offset values (a keyword and a relative numerical value). (We’ll talk about these in more detail in the upcoming sections.)

background-position: top left;
background-position: 50px 30%;
background-position: top 25%;
background-position: right 10px bottom 20px;
background-position: center center
background-position: 10px 20px;
background-position: 5em 2em;
background-position: 75% 50%;

If you provide only one value, the second one is assumed to be center. If you provide two values, the first one determines the offset from the left edge—i.e. the horizontal position, and the second one is the offset down from the top edge—i.e. the vertical position.

background-position: 10% 50%; /* 10% of the width to the right, and 50% down from the top */
background-position: top; /* equivalent to `top center` */
background-position: 50px; /* equivalent to `50px center` */

You can mix and match values, combining lengths with percentages and/or keywords. Note that a pair of keywords can be reordered while a combination of keyword and length or percentage cannot. So center left is valid while 50% left is not—it must be left 50%. When a combination of keyword and a length or percentage value is used, the first value always corresponds to the horizontal offset and the second value to the vertical offset.

As a matter of fact, the keywords are shorthand for specific percentage values. More specifically: top is equivalent to 0% offset from the top edge, bottom is equivalent to 100% offset from the top edge, left is equivalent to 0% offset from the left edge, and right is equivalent to 100% offset from the left edge and center is equivalent to 50% offset in whatever direction (horizontal or vertical) is it applied to.

Let’s start with how each possible value type works—this is probably the most important thing as there is a fundamental difference between the way absolute and percentage values are used by the browser to position background images. We’ll provide more examples as we go.

How Absolute Position Values Work

When you specify a position in absolute units, you’re offsetting the background image’s top left corner by the specified amount. In other words, the image will be moved so that its top left corner is positioned at the offsets specified in your background-position value.

The best way to explain and understand this is to visualise it, so here are two examples of absolute background position values and how they are interpreted by the browser to position the background image. The element in these two examples has 100px by 80px dimensions.

absolute-position-illustration

Positioning a background image using absolute values.

The absolute position can also be negative, in which case the image will be offset in the opposite direction from the edge.

negative-absolute-offset-illustration

Example showing an image offset using a negative offset position value.

Try changing the values of the background position in the following live example to see how the it affects the image. Try negative values too!

See the Pen Adobe background-position Example by Sara Soueidan (@SaraSoueidan) on CodePen.

How Percentage Position Values Work

Unlike the absolute length offset value which moves the element’s top left corner by a specified distance, a percentage X aligns the point at X% across (for horizontal) or down (for vertical) the image with the point at X% across (for horizontal) or down (for vertical) the container.

For example, the percentage value 0% 0% will align the point 0% 0% of the image with the point 0% 0% in the background positioning area’s coordinate system. The position value 50% 75% will align the point that is 50% across and 75% down the image, with the point that is located at 50% 75% in the background positioning area.

Again, a visual example explains it best. Notice how the position value specified is used to get the point of those coordinates inside the image and then aligns that point with the point of the same coordinates in the positioning area.

 

percentage-values-illustration

Positioning a background image using percentage values.

And as with absolute values, you can also specify the percentage offset in negative values, and those will move the background image by the specified value in the opposite direction of the corresponding axis. So a -10% -30% position will offset the image by 10% to the left of the left edge, and 30% upwards.

Play with the values in the following example to see how the background image position changes.

See the Pen Adobe background-position Example#2 by Sara Soueidan (@SaraSoueidan) on CodePen.


The positioning in the previous two examples is done relative to the top and left edges. Now let’s see how we can combine the offset keywords along with the numerical offset values (percentage or absolute) to position images across the background positioning area relative to any of the element’s four edges.

Offsetting Relative to Any Edge

In the examples from the previous two sections, we specified offsets and saw how they are used to offset the image with respect to the top and left edges—which is the default behaviour for one- or two-value positions.

When you combine offset keywords with numerical values for a four-value syntax, you can offset the background image from the right and bottom edges of the positioning area too.

In order to do that, all you have to do is specify the name of the edge you want to use followed by the amount (absolute or percentage) you want to offset it by.

For example, the following are examples of the four-value syntax:

background-position: top 1em right 3em; /* positions the background image 1em down the top edge and 3em left of the right edge */

background-position: right 1em bottom 1em; /* positions the background image 1em above the bottom edge and 1em to the left of the right edge */

background-position: left 20px bottom 50px;

If three out of four values are specified, the fourth value is assumed to be zero.

There is something to keep in mind when using the four-value syntax: When three or four values are given, then each percentage or length represents an offset and must be preceded by a keyword which specifies from which edge the offset is given. For example, background-position: bottom 10px right 20px represents a 10px vertical offset up from the bottom edge and a 20px horizontal offset leftward from the right edge. If three values are given, the missing offset is assumed to be zero. If your provide two numerical offsets and one keyword, the value is invalid and the browser uses the default 0% 0% value.

To get a better grip of this, play with the values of the background-position property in the following live example. The crane background image is first positioned so that it is offset by 0 pixels from the bottom and 2em from the right edge.

See the Pen Adobe background-position by Sara Soueidan (@SaraSoueidan) on CodePen.

This is particularly useful for when you need to position an image at a defined distance from the right and bottom edges, which makes this task much simpler than having to calculate the relative offsets from the top and left edges.

Sizing, Repeating, Clipping and More!

Remember, you can apply multiple background images to an element. For every background image (provided as a list of comma-separated images to background-image), you can specify a corresponding background position; multiple positions are also comma-separated.

All in all, there are nine CSS properties that control the layout, positioning, sizing and painting of background images, including the shorthand background property that is used to set and reset other shorthand properties. Each property allows you to do one thing, and combined they give us great control over how to apply background images to all and any element in HTML. I hope this article has demystified the way positioning background images in CSS works.

In addition to the main background properties, an additional property now exists that allows us to apply blending effects to background images similar to the blending effects available in editors like Photoshop—specifically, the background-blend-mode property. If you’re interested in learning all about blending in CSS, you can read more about it here.

I hope you found this article useful. Thank you for reading.

Comments (0)
Mar
05

Levelling Up With Sass

Posted by: | Comments (0)

Using a CSS preprocessor is fast becoming a crucial part of a developer’s workflow. If it isn’t part of your process yet, consider giving it a try! Check out part 1 of this series and get up to speed with basic features such as nesting selectors, variables and mixins.

Using preprocessors can help organize your CSS and reduce redundancy. However, learning more advanced features will make your CSS even more powerful.

This article will focus on stepping up your game with Sass, though many of these techniques will work using Less as well. Just be sure to note the syntax differences.

Nesting selectors

Nesting and grouping related selectors into one block can make your CSS more organized.

header {
    color: black;

    .logo {
        width: 300px;
    }
    nav {
        font-size: 12px;
    }
}

compiles to:

header {
    color: black;
}
header .logo {
    width: 300px;
}
header nav {i
    font-size: 12px;
}

But what about pseudo selectors or multiple class & id selectors?

a {
    color: #cc0066;

    :hover {
        color: #cccccc;
    }
}

The above example will compile to:

a {
    color: #cc0066;
}
a :hover {
    color: #cccccc;
}

Nested selectors are assumed to be a child element and will automatically add a space between selectors. This is not what we want for psuedo selectors or targeting multiple classes or ids. For this scenario, use the & symbol.

a {
    color: #cc0066;

    &:hover {
        color: #cccccc;
    }
}
.class-one {
    color: #cc0066;

    &.class-two {
        font-size: 16px;
    }
}

The above example will compile to:

a {
    color: #cc0066;
}
a:hover {
    color: #cccccc;
}
.class-one {
    color: #cc0066;
}
.class-one.class-two {
    font-size: 16px;
}

Reminder for nesting selectors, just like Inception, don’t go more than 3 levels deep!

Variables

Variables are super handy, especially for colors. It’s much easier to remember “orange” rather than “#E74C3C”, right? Suppose you decided to use orange as an accent to add a pop of color here and there throughout your web page. Your Sass may look something like this:

$orange: #E74C3C;

h4 {
  background: $orange;
}
a {
  color: $orange;
}

But what if you wanted to change that accent color to blue? You could create a new $blue variable and replace the existing color or change the value of $orange but then the variable name will be confusing!

Use variables as values

If you’re anything like me, I change my mind a lot, so I want my CSS to be able to bend to all my whims as easily as possible. Try using a combination of declaring style and functional naming conventions, then use the variables as a value of another.

$orange: #E74C3C;
$blue: #0000FF;
$primary-color: $orange;
$secondary-color: $blue;

h4 {
  background: $primary-color;
}
a {
  color: $secondary-color;
}

This way, I’m assigning the colors to the selectors based on their function, not the actual color. If I want to change the color, all I’ll have to do is update the variable value, in just one spot!

This technique can work great for font sizing as well, especially when paired with the math capabilities of the language to create relative sizing values.

$base-font-size: 1rem;
$main-heading: $base-font-size + 1; 
$sub-heading: $base-font-size + .5; 
$small-text: $base-font-size - .5;

body {
  font-size: $base-font-size;
}
h1 {
  font-size: $main-heading;
}
h2 {
  font-size: $sub-heading;
}
.footnote {
  font-size: $small-text;
}

The above will compile to:

body {
  font-size: 1rem;
}
h1 {
  font-size: 2rem;
}
h2 {
  font-size: 1.5rem;
}
.footnote {
  font-size: 0.5rem;
}

Comments

You can use two kinds of comment styles in your Sass files. The traditional CSS style, /* comment */ and also the double forward slash style // comment works as well. What’s the difference? The latter does not compile into the .css file. Which is handy for making your CSS files a little bit smaller. (You can also set your Sass compiler to minify your files as well.)

When using CSS preprocessors, you don’t need to edit your .css files anymore so there’s no need for the comments to compile out anyway.

Sass color functions

Some of my favorite Sass functions for creating various color values are lighten(), darken() and rgba().

In many web designs, you will often see variations of the same color. Instead of trying to find a new color value for each variation, use Sass functions!

$grey: #808080;
$grey-dark: darken($grey, 30); // 30% darker
$grey-light: lighten($grey, 10); // 10% lighter

body {
  color: $grey-dark;
}
.footnote {
  color: $grey-light;
}

The above example will compile to:

body {
  color: #343434;
}
.footnote {
  color: #9a9a9a;
}

Sometimes you will need to add an opaque background color to an element. The best way to achieve this without affecting the opacity of the text contained within that element using tradtional CSS, is to use rgba() as your color value like so:

div {
  background: rgba(173, 216, 230, 0.8);
}

The first three numbers represent the red, green and blue values. The last number is the alpha transparency.

What if your Sass variables have been declared in hex values, like in all the previous examples? You could go and find the equivalent RGB value. Or… use a Sass function!

The rgba(color, alpha) Sass function will automatically convert the value for you.

$orange: #E74C3C;
$blue: #0000FF;
$primary-color: $orange;
$secondary-color: $blue;

div {
  background: rgba($orange, 0.8);
}
span {
  background: rgba($secondary-color, 0.8);
}

Compiles to:

div {
  background: rgba(231, 76, 60, 0.8);
}
span {
  background: rgba(0, 0, 255, 0.8);
}

Mixins

And finally, we arrive to mixins. Mixins are handy for multiple CSS declarations that are used together often.

For example, I don’t like to reset all my lists as part of my base CSS but having that option to easily reset a list when needed, is useful. So I’ll create a mixin just for that.

@mixin list-reset() {
  padding: 0;
  margin: 0;

  li {
    display: inline-block;
  }
}
ul.specific-list {
  @include list-reset();
}

Will compile to:

ul.specific-list {
  padding: 0;
  margin: 0;
}
ul.specific-list li {
  display: inline-block;
}

You’ll still be able to add additional styles to that particular list, but using the mixin will make it a little easier to start.

ul.specific-list {
  @include list-reset();
  width: 100%;
}

Compiles to:

ul.specific-list {
  padding: 0;
  margin: 0;
  width: 100%;
}
ul.specific-list li {
  display: inline-block;
}

Mixins and conditionals

Pair mixins with parameters and conditionals to add even more efficiency to your style sheets. For media queries, try something like this:

@mixin max-width($resolution) {
  @if $resolution == large {
    @media only screen and (max-width: 1024px) { @content; }
  }
  @else if $resolution == medium {
    @media only screen and (max-width: 800px) { @content; }
  }
  @else if $resolution == small {
    @media only screen and (max-width: 400px) { @content; }
  }
}

@include max-width(small){
  .some-class {
    width: 100%;
  }
}
@include max-width(large){
  .another-class {
    width: 50%;
  }
}

Compiles to:

@media only screen and (max-width: 400px) {
  .some-class {
    width: 100%;
  }
}
@media only screen and (max-width: 1024px) {
  .another-class {
    width: 50%;
  }
}

Note the @content within the declaration block. In Sass, this directive simply allows
us to pass pretty much anything in between the curly braces, unlike parameters which are specific types of values.

You can use this example to create media query mixins for min-width as well as declaring a range.

These are just a few examples of how you can use Sass to take traditional CSS the next level. See the documentation on the Sass site for even more ideas.

Now that I’ve listed some of my favorite Sass features, please share your favorites in the comments!

Comments (0)

Like most of our ‘Your Questions Answered’ posts, we’re going back to the basics. We get all kinds of questions from our users on our forums, Twitter and Facebook. One question that has come up a bunch, which we’ll be covering in this post, is around creating a table and centering objects using HTML and CSS.
Users that have previously styled tables using HTML will find this tutorial relatively simple. However, if you are new to HTML and CSS, you can still create this table without too much effort. We are using Dreamweaver CC for this tutorial.

Let’s get started.

Create a new page

  1. Open Dreamweaver
  2. Select File > New
  3. In the New Document dialog box, ensure that HTML is selected as the Page type.
  4. Click Create.
  5. In the Code view, locate the tag. In between the opening and closing title tag, enter “Centering objects in a table”.
  6. Select File > Save As and save the file as centering_tables.html.

Create a container for the table

Before we proceed with creating a table, we will be creating a container div tag (containerDiv) to hold the contents of the page, and another container in which we will be placing the table (tableDiv). In the Code editor between the body tags, enter the following code:

<body>
<div class="containerDiv">
<div class="tableDiv">
</div>
</div>
</body>

We now have a container for the contents of the page, and our own DIV for the table that we will be creating now.

Create a table using HTML

Inside the tableDiv container, create a table. Enter ‘Hello’ in each of the cells so that we can see the table clearly in the Design or Live view.

<table>
<tr>
<td>Hello</td>
<td>Hello</td>
<td>Hello</td>
</tr>

<tr>
<td>Hello</td>
<td>Hello</td>
<td>Hello</td>
</tr>
</tr>
</table>

In the Live View or Design View, you should now be able to see a 2×2 table with ‘Hello’ placed in each of the cells. You should also be able to see the container div that is enclosing the table.

hello_code

Style the table

Below the closing title tag, create the opening and closing style tags. Then, use this piece of code to style the table. In the following piece of code, the border-collapse property creates a single continuous border for the table. The rest of the properties are self-explanatory.

.tableStyle{
	border: thin solid #EFEFEF;
	border-collapse:collapse;
	width: 800px;
	margin: 0 auto;
	text-align: center;
	align-items:center;	
	}

In the body, apply the style to the table tag.

Preview the file in a browser using File > Preview in Browser. You should now be able to see the table centered on the page and with a light gray border.

hello_cod2e

Style the cells in the table

We now need separators for each of the cells in the table. Let’s work on that.
Right below the tableStyle in the Style section of the code, enter this piece of code.
Padding will ensure that the text within the cell gets some breathing space.

.tableCell{
	align-content: center;
	border-width: thin;
	border: thin solid #EFEFEF;
	padding: 5px;	
	}

Ensure that you apply the style to all the cells in the table.

Preview your page in a browser. Does it look like this?

hello_code3

The page is centered in its container, and the contents of the table are centered as well.
One last thing you may want to do is to center the entire page in a browser. In which case, we will use this piece of code that we used to center a page.

.containerDiv{
	width: 1200px;
	margin: 0 auto;
		}

And you are done! Check to make sure you got everything right by looking at the final result. Then go ahead and play around with your table. Apply styles, add images, do your thing. Have fun!

Comments (0)

If you use Sass or LESS, then you probably already use variables in your style sheets and know how useful they are. If you don’t use a preprocessor, then you might be curious what the fuss is all about and why variables are so popular and how they can be useful. In this article, we’re going to get an overview of why variables are useful, and get acquainted with one particular variable: currentColor.

What are variables good for?

Variables in CSS are useful because they allow us to write more DRY (Don’t Repeat Yourself) code. They are also particularly useful for managing and maintaining large-scale projects that contain a lot of repeated values.

One of the most common use cases for variables are color themes/schemes throughout a website or application. With variables, creating and managing color schemes across a CSS document becomes a lot easier. For example, color schemes usually require you to reuse a few color values for different properties in the CSS file. If you want to change the primary color of a scheme, you would normally have to change all occurrences of that color in the style sheet. Using CSS variables, you can define a variable in one place (for example a variable named “primary-color”), assign a color value to it, and then use the variable as a value anywhere you want in the style sheet. Then, when the time comes to change this color, all you would have to do is assign it a different color value, and all occurrences of that variable in the style sheet will be automatically updated.

CSS 2.1 did not introduce variables. (Although, that’s not entirely true, as you will see in this article.) In 2014, native CSS variables that are similar to preprocessor variables were introduced; these variables are arguably even more capable than preprocessor variables. A CSS variable is accepted as a value by all CSS properties.

In addition to the new variables, CSS already comes with a keyword value that is practically also a variable: the currentColor keyword.

The currentColor keyword

The currentColor keyword is like a CSS variable, except that it has one main restriction: you can only use it where a <color> value is expected; if a property does not accept a <color> value, it will not accept currentColor as a value.

The following are all examples of using currentColor in properties that accept it as a value.

box-shadow: inset 2px 2px 3px currentColor;
background-color: currentColor; /* not a good idea! */
background-image: linear-gradient(currentColor, transparent);

Another difference between currentColor and other variables is that you don’t get to assign a value to it the same way you would assign other variables values. The value of currentColor is determined by the computed value of the color property that is currently being used on the element. That is, the value of currentColor is equal to the current color property value. And this is where the currentColor name comes from.

So, if we were to go back to our previous example, the currentColor keyword sets the box shadow color to whatever color value you have set on the div. If you haven’t set any color, it will use the inherited color from any of the div’s ancestors. If no ancestor has a color, most browsers will just default to black.

Put another way: the currentColor keyword is used to make properties of an element, or child elements of an element, inherit the color set by the element’s color property. It therefore acts as the inherit value to allow inheritance of a color that would otherwise not be inherited by a property or child element.

This also means that, for properties that already inherit the color value, currentColor will not be of much use.

Properties and elements that inherit the color value by default

When an element has a color value, whether it is explicitly set or inherited, some of the foreground elements of that element that accept a <color> value will inherit that color value by default.

For example, an element’s borders are part of the element’s foreground; thus, even if you don’t specify a border color, the border will get the same color as the color property value. If the element does not have one, most browsers usually default to black.

The border color in this example will be purple:

.parent {
    color: purple;
}

.child {
    border: 5px solid; /* we didn’t specify the border color here */
}

The elements that will get/inherit the element’s color value include:

  • The element’s text—it is what the color property is used for.
  • The text’s outline.
  • The element’s border.
  • The element’s box shadow.
  • An img’s alt text. That is, when the image cannot be displayed, the text that appears in its stead will have that color value.
  • A list item’s bullet(s) and border.
  • In some browsers (e.g Chrome) the horizontal rule’s (<hr>) border color. (Without a border, the color will not be affected.)

When you set these element’s properties on an element without explicitly assigning them a color, they will inherit the computed color value of the element by default.

The following demo shows the above elements in action as they inherit the color set on the page’s body. Change the color property value on the body to see these elements’ colors also change.

See the Pen currentColor — Adobe DW Blog by Sara Soueidan (@SaraSoueidan) on CodePen.

At this point, you might be wondering: if so many properties/elements already inherit the color value, how or where can currentColor be useful?  

Extending color inheritance with currentColor

There are some places where retrieving the color value and using it could come in handy. One example where currentColor can be used that would not otherwise inherit the color value is gradients. CSS gradient images, be that linear or radial gradients, do not inherit colors. By using currentColor, you can make a linear gradient used as a background image, for example, adjust to match any color you specify somewhere else as the “primary color” of a theme.

background-image: linear-gradient(to bottom, currentColor, #fff);

Such an example was created by Scott Kellum who took this concept a little further and added an animation to the color property. As the color property animates, all the elements affected by that color will also animate their colors.   See the Pen currentColor by Scott Kellum (@scottkellum) on CodePen.

This is a great example of using currentColor, particularly the animation part.

However, more practical examples for currentColor exist. Let’s take a look at some of them.

currentColor Use Cases

The idea behind currentColor is to extend the color cascade. This comes in handy in a lot scenarios.

currentColor for theming UI components

From the previous demo, we can move to a more practical (and brilliant, I must say) use case for currentColor demonstrated by Simon “Simurai” in a talk he gave at CSSConfau last year. The talk was about how we can use Flexbox, currentColor and em units inside UI components to quickly style entire Web Apps straight in the browser.

To demonstrate the usefulness of currentColor, Simon created a set of UI elements, including some sliders. These elements have the same color scheme applied. For coloring the sliders and input types, he used the currentColor variable to force the color inheritance in the background color of the slider’s thumb and checkboxes that would otherwise not inherit that color.

currentColor-slider

An example using currentColor to apply the color property’s value to the slider’s thumb. (Source)

Similarly, more UI components can be created that inherit a color value that you would specify somewhere up in the cascade. With this, a UI theme is established on these components. Then, leveraging the cascade and currentColor, you can change the main color value and get a new set of colored components every time you do, thus practically automating the process.

The following GIF image shows that in action. Simon is using the browser devtools and the color picker in the browser to change the value of the color property, and get a live preview of these changes on the components.

Changing the value of the color property will update the colors of all UI components that are inheriting this color, with the help of the currentColor variable. (Source)

 

Using the browser’s devtools capabilities, you would be able to change the theme to your liking and then save the changes to your working files right from the browser. To learn all about it, refer to Simon’s talk and blog post.

currentColor for theming and styling SVG

SVGs are great, but they come with a few styling quirks and limitations depending on how you use them. One such case is reusing parts of an SVG using the SVG <use> element.

If you’re not familiar with the <use> element, you can read all about it here. The idea behind <use> is to reuse parts of an SVG anywhere we want these parts to appear on the page. By useing an SVG element, we’re practically creating a live copy of that element. This is similar to copy-pasting the element in a graphics editor, except that the copy is live—meaning that its characteristics can change as the original copy changes.

The <use> element is used a lot when creating SVG sprites. An SVG containing all of the icons would be used as the sprite, and then we can insert individual icons from that sprite anywhere on the page, using <use>. You can read all about SVG creating sprites in this article.

When an element is used, however, the copy of its contents is cloned into a shadow DOM. This means that these contents cannot be selected and styled with CSS the way we would select and style SVG elements or even HTML elements present in the regular DOM. This is one reason why styling SVG icons created like that is limited.

Using currentColor, we can work around this limitation but allowing a color we specify in CSS “leak” into the contents of the used SVG, by setting currentColor as a value for the properties we want the color value to leak into.

So with an SVG icon used like so:

&lt;svg class="home-icon"&gt;
    &lt;use xlink:href="#home"&gt;&lt;/use&gt;
&lt;/svg&gt;

And assuming the #home icon defined in the sprite sheet contains something like:

&lt;symbol id="home"&gt;
    &lt;rect id="bottom" fill="currentColor" ... /&gt;
    &lt;polygon id="roof" ... /&gt;
&lt;/symbol&gt;

We can then apply styles to the icon and have the fill color cascade down to the #roof (which does not have a fill attribute above) and the color value be inherited by the #bottom rectangle’s fill attribute:

.home-icon {
    fill: red;
    color: white;
}

The fill color will cascade down from the svg to use and then to #roof. The color value will be used as a value for the #bottom fill color because of currentColor.

Fabrice Weinberg wrote an article about this technique a while back on his Codepen blog.

This technique comes in handy when you want to create multiple icons each having different colors; all you would have to do in that case is change the color and fill values in the CSS. An example of this usage is the following demo Fabrice shows in his post:

See the Pen Sass SVG Icons 1.1KB by Fabrice Weinberg (@FWeinb) on CodePen.

Of course, you can use currentColor on multiple elements inside the SVG. However, as you probably have noticed, this only allows you to change two colors inside the SVG.

If you want to have more control over colors and specify more color values that you could leak into the SVG, you would need more variables; this is where the new CSS Variables specification will come in handy. You can read more about this here.

Final Words

In the previous examples, we saw how we can use currentColor in multiple places, and then change the colors we want in one place and have that color be applied to those multiple places, instead of having created multiple occurances of the same color and then changed all of them. This helps us write shorter CSS, and provides us with some sort of automation, especially in situations like the UI components we saw in Simon’s talk.

With CSS Variables, you will be able to define your own set of variables and use them in similar and much, much more use cases, as the new variables will be valid values for any CSS property, not only those that accept <color> values. Dealing with SVG icons will certainly become easier, as will maintaining large-scale projects. Again, if you use a preprocessor, then you already know how useful variables are.

Can you think of more use cases for currentColor? If so, make sure you share them in the comments below!

Comments (0)

Database Design and Management

Cwebpro can design and develop a small business data management solution for you. We will provide professionally crafted entry screens and a database that will grow with your business.

Professional Web Designs

If you need a web site designed or updated contact Matthew at Cwebpro for quality work at a fair price. The Web Creation Zone (Cwebpro) can meet all of your business website design and data management needs.