How to Create The Apple Watch Breathe App Animation with CSS

How to Create The Apple Watch Breathe App Animation with CSS

The Apple Watch comes with a stock app called Breathe that reminds you to… breathe. There’s actually more to it than that, it’s a self wellness app of sorts, that reminds you to take a brief moment out of your stressful day and focus on your breathing to encourage relaxation. Additionally, the app has a minimalistic interface with a nice animation.

I thought it would be fun (and relaxing) to recreate the design, particularly in vanilla CSS. Here’s how far I got, which feels pretty close.

 

Making the circles

First things first, we need a set of circles that make up that flower looking design. The app itself adds a circle to the layout for each minute that is added to the timer, but we’re going to stick with a static set of six for this demo. It feels like we could get tricky by using ::before and ::after to reduce the HTML markup, but we can keep it simple.

<div class="circle"></div>
<div class="circle"></div>
<div class="circle"></div>
<div class="circle"></div>
<div class="circle"></div>
<div class="circle"></div>

We’re going to make the full size of each circle 125px which is an arbitrary number. The important thing is that the default state of the circles should be all of them stacked on top of one another. We can use absolute positioning to do that.

.circle {
  border-radius: 50%;
  height: 125px;
  position: absolute;
  transform: translate(0, 0);
  width: 125px;
}

Note that we’re using the translate function of the transform property to center everything. I had originally tried using basic top, right, bottom, left properties but found later that animating translate is much smoother. I also originally thought that positioning the circles in the full expanded state would be the best place to start, but also found that the animations were cumbersome to create that way because it required resetting each one to center. Lessons learned!

If we were to stop here, there would be nothing on the screen and that’s because we have not set a background color. We’ll get to the nice fancy colors used in the app in a bit, but it might be helpful to add a white background for now with a hint of opacity to help see what’s happening as we work.

 

We need a container!

You may have noticed that our circles are nicely stacked, but nowhere near the actual center of the viewport. We’re going to need to wrap these bad boys in a parent element that we can use to position the entire bunch. Plus, that container will serve as the element that pulses and rotates the entire set later. That was another lesson I had to learn the hard way because I stubbornly did not want the extra markup of a container and thought I could work around it.

We’re calling the container .watch-face here and setting it to the same width and height as a single circle.

<div class="watch-face">
  <div class="circle"></div>
  <div class="circle"></div>
  <div class="circle"></div>
  <div class="circle"></div>
  <div class="circle"></div>
  <div class="circle"></div>
</div>

Now, we can add a little flex to the body element to center everything up.

body {
  background: #000;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;
}

 

Next up, animate the circles

At this point, I was eager to see the circles positioned in that neat floral, overlapping arrangement. I knew that it would be difficult to animate the exact position of each circle without seeing them positioned first, so I overrode the transform property in each circle to see where they’d land.

We could set up a class for each circle, but using :nth-child seems easier.

.circle:nth-child(1) {
  transform: translate(-35px, -50px);
}

/* Skipping 2-5 for brevity... */

.circle:nth-child(6) {
  transform: translate(35px, 50px);
}

It took me a few swings and misses to find coordinates that worked. It ultimately depends on the size of the circles and it may take some finessing.

 

Armed with the coordinates, we can register the animations. I removed the transform coordinates that were applied to each :nth-child and moved them into keyframes:

@keyframes circle-1 {
  0% {
    transform: translate(0, 0);
  }
  100% {
    transform: translate(-35px, -50px);
  }
}

/* And so on... */

I have to admit that the way I went about it feels super clunky because each circle has it’s own animation. It would be slicker to have one animation that can rule them all to push and re-center the circles, but maybe someone else reading has an idea and can share it in the comments.

Now we can apply those animations to each :nth-child in place of transform:

.circle:nth-child(1) {
  animation: circle-1 4s ease alternate infinite;
}

/* And so on... */

Note that we set the animation-timing-function to ease because that feels smooth…at least to me! We also set the animation-direction to alternate so it plays back and forth and set the animation-iteration-count to inifinite so it stays running.

 

Color, color, color!

Oh yeah, let’s paint this in! From what I can tell, there are really only two colors in the design and the opacity is what makes it feel like more of a spectrum.

The circles on the left are a greenish color and the ones on the right are sorta blue. We can select the odd-numbered circles to apply the green and the even-numbered ones to apply the blue.

.circle:nth-child(odd) {
  background: #61bea2;
}

.circle:nth-child(even) {
  background: #529ca0;
}

Oh, and don’t forget to remove the white background from the .circle element. It won’t hurt anything, but it’s nice to clean up after ourselves. I admittedly forgot to do this on the first go.

 

It’s also at this point that others in the comments have suggested that replacing opacityfor mix-blend-mode with a value of screen makes for a nicer way to blend the colors of the circles. I’ve since updated the demos and the code.

Pulse and rotate

Remember that pesky .watch-face container we created? Well, we can animate it to pulse the circles in and out while rotating the entire bunch.

I had totally forgotten that transform functions can be chained together. That makes things a little cleaner because it allows us to apply scale() and rotate() on the same line.

@keyframes pulse {
  0% {
    transform: scale(.15) rotate(180deg);
  }
  100% {
    transform: scale(1);
  }
}

…and apply that to the .watch-face element.

.watch-face {
  height: 125px;
  width: 125px;
  animation: pulse 4s cubic-bezier(0.5, 0, 0.5, 1) alternate infinite;
}

Like the circles, we want the animation to run both ways and repeat infinitely. In this case, the scale drops to a super small size as the circles stack on top of each other and the whole thing rotates halfway on the way out before returning back on the way in.

I’ll admit that I am not a buff when it comes to finding the right animation-timing-function for the smoothest or exact animations. I played with cubic-bezier and found something I think feels pretty good, but it’s possible that a stock value like ease-in would work just as well.

All together now!

Here’s everything smushed into the same demo.

 

If you’re having a stressful day, even you don’t have an apple watch, you can gaze into the CSS animation you’ve created and lull yourself into tranquility.

Make sure you don’t keep all of this peacefulness to yourself, and pass along your newly discovered knowledge. 

For all things Apple, check out all of our latest Apple related guides.

references: apple, css tricks, codepen, mozilla

CSS Transitions and Animations: Intro Guide

CSS Transitions and Animations: Intro Guide

I’ve noticed in the comments of other posts recently that some readers would like more “tips and tricks” articles, particularly about CSS. So in today’s post, I’ll be providing what I hope is a useful introduction to a bit of CSS “trickery” that can be used to create compelling microinteractions across your website. Specifically, we’ll be learning how to create CSS transitions and animations. We’ll also be talking about when and where you might want to use them.

What Are CSS Transitions and Animations?

The evolution of CSS over the years has lead to some really amazing innovations within the language. In the case of transitions and animations, what previously required a program like Adobe Flash or another coding language altogether (such as Javascript) is now possible with nothing but HTML and CSS.

This kind of language maturity, enabled by better browsers and higher web standards (among other things), has been a huge boon to web designers who double as front end developers. They can now do more with less and the whole process of web design/development has become a bit easier.

Nevertheless, CSS transitions and animations are still considered advanced uses of CSS. A spectrum of coding I try to stay away from in most of my articles since I do not consider myself an “advanced developer”–even in language as accessible as HTML or CSS.

That said though, after reading up on W3Schools and elsewhere I think a sufficiently simple introduction to these concepts is within the grasp of not only myself but a good deal of the WTG readership as well.

To begin, I think we need to have a really good idea of what, exactly, CSS transitions and animations are before jumping into examples and code.

CSS Transitions

A CSS transition allows you to change the property values of an element over a given duration that you set. To create a transition you must first identify which CSS property you want to add an effect to and then specify the duration of the effect. If no duration is set, the transition will not occur.

There are four transition properties:

transition-delay – specifies the delay, in seconds (s), you would like to assign your transition effect.

transition-duration – specifies the duration, in seconds (s) or milliseconds (ms), you would like to assign your transition effect.

transition-property – specifies the name of the CSS property your transition effect is meant for.

transition-timing-function – Specifies the speed curve of the transition effect. Meaning, the type of speed variation you want to select for your transition effect. There is no “fast” or “slow” options. Instead there are speed curve options that go from one speed to another. Such as “ease” which tells your effect to start slow, then go fast, then end slowly.

To create a transition you only need to change one of these properties over the duration you choose. However, it is possible to change more than one property at the same time; resulting in more dramatic transitions.

CSS Animations

Where CSS transitions are all about altering element properties as they move from state to state, CSS animations are dependent on keyframes and animation properties.

keyframes – keyframes are used to define the styles an element will have at various times.

animation properties – animation properties are used to assign @keyframes to a specific element and determine how it is animated.

There are eight animation properties:

animation-delay – specifies a delay for the start of an animation.

animation-direction – specifies whether an animation should play in reverse direction or alternate cycles.

animation-duration – specifies how many seconds or milliseconds an animation takes to complete one cycle.

animation-fill-mode – specifies a style for the element when the animation is not playing. Such as when it is finished or when it has a delay.

animation-iteration-count – specifies the number of times an animation should be played.

animation-name – specifies the name of the @keyframes animation.

animation-play-state – specifies whether the animation is running or paused.

animation-timing-function – specifies the speed curve of the animation.

The examples below will show you how these things are used together in various ways. Once you understand the relationships between them you’ll be able to figure out all kinds of interesting ways to use them.

A Quick Note on Vendor Prefixes

In your personal usage of CSS transitions and animations you will most likely need to use vendor prefixes. In some of the code below you will no doubt notice some vendor prefixes. Many of the source examples do not contain vendor prefixes, so if you want to see what the code looks like without them you can check there; I thought it might be helpful to provide a fuller picture.

For the uninitiated, when I say “vendor prefix” I’m referring to a prefix that needs to be added to your CSS based on the range of browsers you want to support your transitions and animations.

A good resource for identifying the necessary prefixes for each browser is caniuse.com. You can also check out the respective pages for transitions and animations on W3Schools. Or, if you’d like to avoid the mess of prefixes altogether, you can use a tool like Bourbon.io.

CSS Transition Examples

The CSS transition examples below are all transitions I’ve found from various sources that show what’s possible with these relatively new CSS capabilities. I’ve chosen to recreate the examples I found using CodePen so you can easily take a peak at the HTML and CSS required for each example while also seeing it in action
1. Linear

Example via.

2. Spin

Example via.

3. Color

Example via.

4. Square to Circle

Example via.

5. Card

Example via.

CSS Animation Examples

Again, the CSS animation examples below are from various sources around the web. Just as above, the CodePen allows you to see the animation and the required code in one place. You can also follow my source links to get more information (in some cases) on each example.
1. Pulse

Example via.

2. Shake

Example via.

3. Bouncing

Example via.

4. Bounce In

Example via.

5. Linear Bar

Example via.

Potential Use Cases for CSS Transitions & Animations

As I mentioned above, CSS transitions and animations are ideal for creating compelling and delightful microinteractions across your website. A lot of great WordPress themes and plugins come with some of these behaviors in place. A good example being the Divi Builder, which allows you to control transitions and animations within its module controls.

You may however wish to take the basics above and apply them other areas of your site in which a theme or plugin author has not given you easy control over. The following ideas might help you get started.

  • An email opt-in form that makes a delightful entrance and exist; such as bouncing in and folding closed to disappear.
  • A form that shakes when the essential information is not and someone attempt to submit it as finished.
  • Buttons that fold open, bounce, shake, or in some other way respond to hovering and clicking.
  • Preview images that turn over to reveal more information.
  • Subtle background graphics that move, creating depth.
  • Beautiful charts that spring into action as they load.
  • Google Doodle style experiments, logos, and more.
  • Games (for the really ambitious).
  • Ads that you can interact with or that subtly change shape to draw attention.
  • Beautiful product displays that rotate and respond to the mouse.
  • Beautiful stat counters.
  • And whatever else your imagination can think up.

Inspiring Showcases of CSS Transitions and Animations

If you need more visual stimulus than a list of ideas, I’ve take the liberty of compiling a small but impressive showcase of inspiring CSS transitions and animations that I hope will show off the potential illustrated in the rather basic examples I created above.

Logos in Pure CSS

Logos-In-Pure-CSS

Logos in Pure CSS is a great showcase of world famous logos re-created with nothing but CSS. In their current form they use animations and transitions to show how they are made and how they stack up against their traditional counterparts. However, I think it’s important to note that just creating your logo in HTML/CSS opens up a lot of interesting possibilities.

Go to Logos in Pure CSS

CSS A/Z

CSS-A-Z

CSS A/Z is a showcase of HTML/CSS animated sketches; one for each letter of the alphabet. Great stuff and a lot of ideas for sprucing up seemingly insignificant elements on your website.

Go to CSS A/Z

Double Ring

Double-ring

I think Double Ring is a great example of something you could do with a logo to make it more eye catching and interesting.

Go to Double Ring

Navigation Bar

nav-bar

Navigation Bar is an example of just how dynamic and beautiful something as standard as navigation can become when given some advanced CSS love.

Go to Navigation Bar

In Pieces

In-Pieces

In Pieces is a magnificent (and highly complex) use case of CSS animation. It’s an interactive exhibition of the evolution of 30 species of animals. Truly breathtaking and a great indicator of just how powerful a tool CSS can be.

Go to In Pieces

Additional Resources & Tutorials

In your quest to master CSS transitions and animations, there is a good chance that you’ll need or want more detail than I am able to provide in this post. Additionally, someone else’s writing style may be a bette fit for the way you think. That’s why I’ve compiled a short list of other useful resources and tutorials below for you to take advantage of.

In Conclusion

CSS transitions and animations are an extremely useful and versatile set of capabilities. You can do small subtle things or big in-your-face impressive things. But either way, it all starts with mastering the basics and moving on from there.

I hope this post is a welcome change of pace for those who have been requesting more CSS related content. If you have any more thoughts or requests on this post or future posts then please feel free to drop us a line in the comments section below.

references: elegant themes, w3schools, shayhowe, caniuse, bourbon

Data Table with CSS – Learn How to Tame

Data Table with CSS – Learn How to Tame

A data table can be a pain to work with, perhaps comparable to herding cats or taming a lion.  Tons of similar-looking, heavily-nested markup can be viewed as completely inflexible. One of the biggest problems I ever encountered was working on a particular company, whose content was almost exclusively data tables, it involved making tables’ cells line up nicely not only with each other, but also with those cells in other tables on the page.

Example of a data table with css:

The problems

There are a lot of headaches we encounter when building tables, and I imagine most of you reading this article will nod along to every point I make; it will be something that will have annoyed us all at some point or another. What this particular (and very specific) problem boils down to is trying to consistently format, size and align complex data layouts across multiple tables. Imagine a financial report; loads of tables of data with differing numbers of cells and columns that—from a purely aesthetic perspective—need to line up in some neat, coherent fashion. Achieving this is made very difficult by a number of different factors…

Cell widths

Tables lay out their cells—by default—in a rather unusual, almost haphazard way. There seems to be no rhyme or reason behind how and why they are rendered at the widths they are, which leads to columns and cells of differing sizes.

Spanning cells

In order to have cells span several columns (and rows, but that doesn’t pose the same problems), we have to use the colspan attribute. To have a cell spanning two columns we would write <t[h|d] colspan="2">. These are often unmanageable, and it can be confusing to remember what all your colspans should add up to.

Knock-on effects

Resizing one cell in one row can, and usually will, affect the layout of the entire table. This is is because all cells’ boundaries have to line up with the boundaries of the rest of the row and column in which it sits. You can’t just change the width of one cell, you have to change them all. This means that, for example, spanning one cell across xcolumns might mean having to update a whole load more colspans elsewhere in thetable.

Tables next to tables

The above problems are further compounded when you begin laying out multiple different tables on any given page. In Sky Bet world, this was pretty much every page. One table’s rendered layout might be vastly different to the tables above and/or below it, creating an unsightly mess of misaligned columns. You might have a tablewith no colspans above a table with some colspans, above a table with lots of awkward colspans. You might have a table with lots of cells above a table with very few. You might have any combination of amounts of cells and amounts of colspans. It all gets very hairy, very quickly.

Solution

I’ve come up with what I feel is a solid, very pragmatic solution.

There are two parts to solving this problem. Firstly we need to standardize the number of cells in every table, and then we need to force these cells to all be the same width. Think of this as a grid system for tables.

24 cells

Think about page layouts that adhere to a grid system; you might have a 24 column grid, but your page might only have two main columns which span, say, 16 and eight columns respectively. You can’t see the 24 columns, but they’re there. You might then have a large footer broken into three columns of eight (again, adding up to 24).

We need to apply this model to tables; we shall give all tables 24 columns, and then use a generous amount of colspans to knock our cells through into each other, into more useful layouts. Now every table we build will be based on a 24 column grid which will, firstly, make everything more consistent, and, secondly, it will make our maths much simpler. We just need to make sure every row’s colspan values add up to 24 every time.

This does mean that every cell in the table now has to carry a colspan, but as I said, this solution is a pragmatic one.

The reason we pick 24 is because it can take halves, thirds, quarters, sixths, eighths and twelfths; we can make a lot of layouts if we have 24 columns to play with.

Now, we would write this snippet:

...
    <th>Column one</th>
    <th>Column two</th>
    <th>Column three</th>
...

as:

...
    <th colspan="8">Column one</th>
    <th colspan="8">Column two</th>
    <th colspan="8">Column three</th>
...

For all this is more markup, it does mean we can begin to standardise our tables’ layouts so that multiple tables on the same page can share a lowest common multiple and are now able to be aligned to one another.

The short version of this section is basically: we are setting up a grid system for ourtables.

Equal width columns

It’s all well and good that all our tables have the same number of columns, but that doesn’t escape the fact that browsers will still render every table differently, and that the size of these cells will always vary. There’s no point having a 24 column table-grid-system if each column is a different width. Thankfully, this is the easiest part of the puzzle to solve and, probably, the most interesting part of this article: table-layout: fixed;.

Now it’s time to tame a data table with css.

There is a little known, and even less used, CSS property called table-layout. table-layout basically tells a browser how to render the columns in a table, and is, by default, set to auto. auto means that the browser will automatically render the cells in a table based on their width, which leads to the differently and inconsistently sized columns.

Interestingly, table-layout: fixed; is the backbone of my pure CSS, equal-width tabs.

Setting table-layout to fixed however, tells the browser to render every cell the same width as each other. Equally-sized table cells right out of the box!

Combining the two

By giving our tables a common grid system of 24 columns, and ensuring these columns are all of equal width, we can begin throwing together all manner of layouts.

I would propose that you opt into the table-grid-system via a simple helper class, perhaps .table-grid:

.table-grid {
    table-layout: fixed;
}

Every time we want to build a table to a fixed and consistent layout, we simply invoke the grid and lay it out to that.

Hopefully now you’ve gained an edge and can control a data table with css on your project(s).


references: csswizardy

Single Responsibility Principle for CSS

Single Responsibility Principle for CSS

The single responsibility principle is a paradigm that, very loosely, states that all pieces of code (in our case, classes) should focus on doing one thing and one thing only. More formally:

…the single responsibility principle states that every context (class, function, variable, etc.) should have a single responsibility, and that responsibility should be entirely encapsulated by the context.

What this means for us is that our CSS should be composed of a series of much smaller classes that focus on providing very specific and limited functionality. This means that we need to decompose UIs into their smallest component pieces that each serve a single responsibility; they all do just one job, but can be very easily combined and composed to make much more versatile and complex constructs. Let’s take some example CSS that does not adhere to the single responsibility principle:

.error-message {
    display: block;
    padding: 10px;
    border-top: 1px solid #f00;
    border-bottom: 1px solid #f00;
    background-color: #fee;
    color: #f00;
    font-weight: bold;
}

.success-message {
    display: block;
    padding: 10px;
    border-top: 1px solid #0f0;
    border-bottom: 1px solid #0f0;
    background-color: #efe;
    color: #0f0;
    font-weight: bold;
}

Here we can see that—despite being named after one very specific use-case—these classes are handling quite a lot: layout, structure, and cosmetics. We also have a lot of repetition. We need to refactor this in order to abstract out some shared objects (OOCSS) and bring it more inline with the single responsibility principle. We can break these two classes out into four much smaller responsibilities:

.box {
    display: block;
    padding: 10px;
}


.message {
    border-style: solid;
    border-width: 1px 0;
    font-weight: bold;
}

.message--error {
    background-color: #fee;
    color: #f00;
}

.message--success {
    background-color: #efe;
    color: #0f0;
}

Now we have a general abstraction for boxes which can live, and be used, completely separately from our message component, and we have a base message component that can be extended by a number of smaller responsibility classes. The amount of repetition has been greatly reduced, and our ability to extend and compose our CSS has been greatly increased. This is a great example of OOCSS and the single responsibility principle working in tandem.

By focussing on single responsibilities, we can give our code much more flexibility, and extending components’ functions becomes very simple when sticking to the open/closed principle.

reference: css guidelines

Learn How to Create 5 Incredible CSS Animations

Learn How to Create 5 Incredible CSS Animations

You’ve probably noticed that more and more CSS animation examples have been appearing on websites lately. Web designers are getting creative and using CSS animations to bring personality to their sites, capture complex ideas effortlessly, and subtly guide their users’ actions.

The golden rule here is that your CSS animations shouldn’t be overblown – even a subtle movement can have a big impact. The best animations you see online still can have their roots in Disney’s classic 12 principles of animation. 

Here, I’ve pulled together a selection of some interesting CSS animation examples from websites around the world, and dug into the code to show you how to achieve these effects yourself.

What is a CSS animation?

CSS animation is a method of animating certain HTML elements without having to use processor and memory-hungry JavaScript or Flash. There’s no limit to the number or frequency of CSS properties that can be changed. CSS animations are initiated by specifying keyframes for the animation: these keyframes contain the styles that the element will have.

1. Rising Bubbles

The CSS bubble animation that features on 7UP is a beautiful example of carrying a brand theme through into the website design. The animation consists of a few elements: the SVG ‘drawing’ of the bubbles and then two animations applied to each bubble. 

The first animation changes the opacity of the bubble and moves it vertically in the view box; the second creates the wobbling effect for added realism. The offsets are handled by targeting each bubble and applying a different animation duration and delay.

In order to create our bubbles we’ll be using SVG. In our SVG we create two layers of bubbles: one for the larger bubbles and one for the smaller bubbles. Inside the SVG we position all of our bubbles at the bottom of the view box.

<g class="bubbles-large" stroke-width="7">
  <g transform="translate(10 940)">
  <circle cx="35" cy="35" r="35"/>
  </g>
  ...
</g>
<g class="bubbles-small" stroke-width="4">
  <g transform="translate(147 984)">
  <circle cx="15" cy="15" r="15"/>
  </g>
</g>
  ...
</g>

In order to apply two separate animations to our SVGs, both utilising the transform property, we need to apply the animations to separate elements. The <g> element in SVG can be used much like a div in HTML; we need to wrap each of our bubbles (which are already in a group) in a group tag.

<g>
  <g transform="translate(10 940)">
  <circle cx="35" cy="35" r="35"/>
  </g>
</g>

CSS has a powerful animation engine and really simple code in order to produce complex animations. We’ll start with moving the bubbles up the screen and changing their opacity in order to fade them in and out at the beginning and end of the animation.

@keyframes up {
  0% {
  opacity: 0;
  }
  10%, 90% {
  opacity: 1;
  }
  100% {
  opacity: 0;
  transform: translateY(-1024px);
  }
}

In order to create a wobbling effect, we simply need to move (or translate) the bubble left and right, by just the right amount – too much will cause the animation to look too jaunting and disconnected, while too little will go mostly unnoticed. Experimentation is key with when working with animation.

@keyframes wobble {
  33% {
  transform: translateX(-50px);
  }
  66% {
  transform: translateX(50px);
  } }

In order to apply the animation to our bubbles, we’ll be using the groups we used earlier and the help of nth-of-type to identify each bubble group individually. We start by applying an opacity value to the bubbles and the will-change property in order to utilise hardware acceleration.

.bubbles-large > g {
  opacity: 0;
will-change: transform, opacity;}
.bubbles-large g:nth-of-type(1) {...}
...
.bubbles-small g:nth-of-type(10) {...}

We want to keep all the animation times and delays within a couple of seconds of each other and set them to repeat infinitely. Lastly, we apply the ease-in-outtiming function to our wobble animation to make it look a little more natural.

.bubbles-large g:nth-of-type(1) {
  animation: up 6.5s infinite; }
.bubbles-large g:nth-of-type(1) circle {
  animation: wobble 3s infinite ease-in-out; }
...
bubbles-small g:nth-of-type(9) circle {
  animation: wobble 3s 275ms infinite ease-in-out; }
.bubbles-small g:nth-of-type(10) {
animation: up 6s 900ms infinite;}

2. Scrolling Mouse

A subtle scrolling mouse animation can give direction to the user when they first land on a website. Although this can be accomplished using HTML elements and properties, we’re going to use SVG as this is more suited to drawing.

Inside our SVG we need a rectangle with rounded corners and a circle for the element we’re going to animate, by using SVG we can scale the icon to any size we need.

<svg class="mouse" xmlns="..." viewBox="0 0 76 130" preserveAspectRatio="xMidYmid meet">
  <g fill="none" fill-rule="evenodd">
  <rect width="70" height="118" x="1.5" y="1.5" stroke="#FFF" stroke-width="3" rx="36"/>
  <circle cx="36.5" cy="31.5" r="4.5" fill="#FFF"/>
  </g>
</svg>

Now we’ve created our SVG, we need to apply some simple styles in order to control the size and position of the icon within our container. We’ve wrapped a link around the mouse SVG and positioned it to the bottom of the screen.

.scroll-link {
  position: absolute;
  bottom: 1rem;
  left: 50%;
  transform: translateX(-50%);
}
.mouse {
  max-width: 2.5rem;
  width: 100%;
  height: auto;
}

Next we’ll create our animation. At 0 and 20 per cent of the way through our animation, we want to set the state of our element as it begins. By setting it to 20% of the way through, it will stay still for part of the time when repeated infinitely.

@keyframes scroll {
  0%, 20% {
  transform: translateY(0) scaleY(1);
  }
}

We need to add in the opacity start point and then transform both the Y position and the vertical scale at the 100% mark, the end of our animation. The last thing we need to do is drop the opacity in order to fade out our circle.

@keyframes scroll {
  ...
  10% {
  opacity: 1;
  }
  100% {
  transform: translateY(36px) scaleY(2);
  opacity: 0.01;
  }
}

Lastly we apply the animation to the circle, along with the ‘transform-origin’ property and the will-change property to allow hardware acceleration. The animation properties are fairly self-explanatory. The cubic-bezier timing function is used to first pull the circle back before dropping it to the bottom of our mouse shape; this adds a playful feel to the animation.

.scroll {
  animation-name: scroll;
  animation-duration: 1.5s;
  animation-timing-function: cubic-bezier(0.650, -0.550, 0.250, 1.500);
  animation-iteration-count: infinite;
  transform-origin: 50% 20.5px;
  will-change: transform;
}

3. Spinning Circles

The animated loading icon is made up of four circles. The circles have no fill, but have alternating stroke-colours.

<svg class="loader" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 340 340">
  <circle cx="170" cy="170" r="160" stroke="#E2007C"/>
  <circle cx="170" cy="170" r="135" stroke="#404041"/>
  <circle cx="170" cy="170" r="110" stroke="#E2007C"/>
  <circle cx="170" cy="170" r="85" stroke="#404041"/>
</svg>

In our CSS, we can set some basic properties to all of our circles and then use the :nth-of-type selector to apply a different stroke-dasharray to each circle.

circle:nth-of-type(1) {
  stroke-dasharray: 550; 
}
circle:nth-of-type(2) {
  stroke-dasharray: 500; 
}
circle:nth-of-type(3) {
  stroke-dasharray: 450;}
circle:nth-of-type(4) {
  stroke-dasharray: 300; 
}

Next, we need to create our keyframe animation. Our animation is really simple: all we need to do is to rotate the circle by 360 degrees. By placing our transformation at the 50% mark of the animation, the circle will also rotate back to its original position.

@keyframes preloader {
  50% {
  transform: rotate(360deg);
  } 
}

With our animation created, we now just need to apply it to our circles. We set the animation name; duration; iteration count and timing function. The ‘ease-in-out’ will give the animation a more playful feel. 

animation-name: preloader;
animation-duration: 3s;
animation-iteration-count: infinite;
animation-timing-function: ease-in-out;

At the moment, we have our loader, but all of the elements are rotating together at the same time. To fix this, we’ll apply some delays. We’ll create our delays using a Sass for loop.

@for $i from 1 through 4 {
  &:nth-of-type(#{$i}) {
  animation-delay: #{$i * 0.15}s;
} }

Due to the delays, our circle now animates in turn, creating the illusion of the circles chasing each other. The only problem with this is that when the page first loads, the circles are static, then they start to move, one at a time. We can achieve the same offset effect, but stop the unwanted pause in our animation by simply setting the delays to a negative value.

animation-delay: -#{$i * 0.15}s;

4. Flying Birds

We start with completely straight vector lines, drawing each frame of our animation, depicting the bird in a different state of flight. We then manipulate the vector points and round the lines and edges. Finally, we put each frame into an equally sized box and place them side-by-side. Export the file as an SVG.

The HTML setup is really simple. We just need to wrap each bird in a container in order to apply multiple animations – one to make the bird fly and the other to move it across the screen.

<div class="bird-container">
  <div class="bird"></div>
</div>

We apply our bird SVG as the background to our bird div and choose the size we want each frame to be. We use the width to roughly calculate the new background position. The SVG has 10 cells, so we multiply our width by 10 and then alter the number slightly until it looks correct.

.bird {
  background-image: url('bird.svg');
  background-size: auto 100%;
  width: 88px;
  height: 125px;
  will-change: background-position;
}
@keyframes fly-cycle {
  100% {
  background-position: -900px 0;
  } 
}

CSS animation has a couple of tricks you may not be aware of. We can use the animation-timing-function to show the image in steps – much like flicking through pages in a notebook to allude to animation.

animation-name: fly-cycle;
animation-timing-function: steps(10);
animation-iteration-count: infinite;
animation-duration: 1s;
animation-delay: -0.5s;

Now we’ve created our fly cycle, our bird is currently flapping her wings but isn’t going anywhere. In order to move her across the screen, we create another keyframe animation. This animation will move the bird across the screen horizontally while also changing the vertical position and the scale to allow the bird to meander across more realistically.

Once we’ve created our animations, we simply need to apply them. We can create multiple copies of our bird and apply different animation times and delays. 

.bird--one {
  animation-duration: 1s;
  animation-delay: -0.5s;
}
.bird--two {
  animation-duration: 0.9s;
  animation-delay: -0.75s;
}

5. Hamburger Crossing

This animation is used all over the web, turning three lines into a cross or close icon. Until fairly recently, the majority of implementations have been achieved using HTML elements, but actually SVG is much more suited to this kind of animation – there’s no longer a need to bloat your buttons code with multiple spans. 

Due to the animatable nature and SVG and its navigable DOM, the code to accomplish the animation or transition changes very little – the technique is the same. 

We start by creating four elements, be it spans inside of a div or paths inside of an SVG. If we’re using spans, we need to use CSS to position them inside the div; if we’re using SVG, this is already taken care of. We want to position lines 2 and 3 in the centre – one on top of another – while spacing lines 1 and 4 evenly above and below, making sure to centre the transform origin.

We’re going to rely on transitioning two properties: opacity and rotation. First of all, we want to fade out lines 1 and 4, which we can target using the :nth-child selector.

.menu-icon.is-active {element-type}:nth-child(1),
.menu-icon.is-active {element-type}:nth-child(4) {
  opacity: 0; }

The only thing left to do is target the two middle lines and rotate them 45 degrees in opposite directions.

.menu-icon.is-active {element-type}:nth-child(2) {
  transform: rotate(45deg); }
.menu-icon.is-active {element-type}:nth-child(3) {
transform: rotate(-45deg); } 

references: codepen, creativebloq

If you want to compare css animations vs javascript check out this guide.

If you want even more info check out these products below:

CSS Media Queries for Samsung Galaxy Devices

/* ----------- Galaxy S3 ----------- */

/* Portrait and Landscape */
@media screen
and (device-width: 360px)
and (device-height: 640px)
and (-webkit-device-pixel-ratio: 2) {

}

/* Portrait */
@media screen
and (device-width: 320px)
and (device-height: 640px)
and (-webkit-device-pixel-ratio: 2)
and (orientation: portrait) {

}

/* Landscape */
@media screen
and (device-width: 320px)
and (device-height: 640px)
and (-webkit-device-pixel-ratio: 2)
and (orientation: landscape) {

}

/* ----------- Galaxy S4, S5 and Note 3 ----------- */

/* Portrait and Landscape */
@media screen
and (device-width: 320px)
and (device-height: 640px)
and (-webkit-device-pixel-ratio: 3) {

}

/* Portrait */
@media screen
and (device-width: 320px)
and (device-height: 640px)
and (-webkit-device-pixel-ratio: 3)
and (orientation: portrait) {

}

/* Landscape */
@media screen
and (device-width: 320px)
and (device-height: 640px)
and (-webkit-device-pixel-ratio: 3)
and (orientation: landscape) {

}

/* ----------- Galaxy S6 ----------- */

/* Portrait and Landscape */
@media screen
and (device-width: 360px)
and (device-height: 640px)
and (-webkit-device-pixel-ratio: 4) {

}

/* Portrait */
@media screen
and (device-width: 360px)
and (device-height: 640px)
and (-webkit-device-pixel-ratio: 4)
and (orientation: portrait) {

}

/* Landscape */
@media screen
and (device-width: 360px)
and (device-height: 640px)
and (-webkit-device-pixel-ratio: 4)
and (orientation: landscape) {

}

references: css tricks

What are CSS Sprites and How Do You Use Them?

What are CSS Sprites and How Do You Use Them?

What are CSS Sprites?

Spoiler alert: they aren’t little creatures with wings that write your stylesheets for you. In short: CSS Sprites are a means of combining multiple images into a single image file for use on a website, to help with performance.

Sprite may seem like a bit of a misnomer considering that you’re creating a large image as opposed to working with many small ones, but the history of sprites, dating back to 1975, should help clear things up.

To summarize: the term “sprites” comes from a technique in computer graphics, most often used in video games. The idea was that the computer could fetch a graphic into memory, and then only display parts of that image at a time, which was faster than having to continually fetch new images. The sprite was the big combined graphic.

CSS Sprites is pretty much the exact same theory: get the image once, and shift it around and only display parts of it. This reduces the overhead of having to fetch multiple images.

Why use CSS Sprites?

It may seem counterintuitive to cram smaller images into a larger image. Wouldn’t larger images take longer to load?

Let’s look at some numbers on an actual example:

ImageFile SizeDimensions
canada.png1.95KB256 x 128
usa.png3.74KB256 x 135
mexico.png8.69KB256 x 147

That adds up to a total of 14.38KB to load the three images. Putting the three images into a single file weighs in at 16.1KB. The sprite ends up being 1.72KB larger than the three separate images.This isn’t a big difference, but there needs to be a good reason to accept this larger file… and there is!

While the total image size (sometimes) goes up with sprites, several images are loaded with a single HTTP request. Browsers limit the number of concurrent requests a site can make and HTTP requests require a bit of handshaking.

Thus, sprites are important for the same reasons that minifying and concatinating CSS and JavaScript are important.

How do you use CSS Sprites?

Here’s an example sprite, with three different countries flags combined into a single image:

You set the same background-image on several CSS classes and set the background position and dimensions of the individual classes to display a single portion of the sprite. Here’s some code that demonstrates the concept:

.flags-canada, .flags-mexico, .flags-usa {
  background-image: url('../images/flags.png');
  background-repeat: no-repeat;
}

.flags-canada {
  height: 128px;
  background-position: -5px -5px;
}

.flags-usa {
  height: 135px;
  background-position: -5px -143px;
}

.flags-mexico {
  height: 147px;
  background-position: -5px -288px;
}

If you’re thinking that there has to be a way to automate this so that you aren’t manually creating these sprites and then adjusting your stylesheet to match, you’re right, and you’re in luck!

Generate Sprites with Grunt / Gulp / Node

If you’re using Grunt, Gulp, or Node in general, css-sprite (now called sprity) is a wonderful node package that creates sprites from a glob of images. Sprity has a lot of great features including formatting output as PNG, JPG (or Data URIs of those), and stylesheet generation in CSS, LESS, Sass, and Stylus.

To compile sprites via command line, install css-sprite globally with:

$ npm install sprity -g

Then, to generate sprites and the corresponding stylesheet, run:

$ sprity ./output-directory/ ./input-directory/*.png

For more information on using css-sprite with Grunt or Gulp (or many other environments), head over to the project’s repository on GitHub.

Generate Sprites with Compass

Generating sprites with Compass takes some additional setup and maintenance, but if you’re already using Compass, it fits in well with your existing workflow.

Start by creating a directory within your `images` directory (yes, it does need to be inside your `images` directory to work) with a name that corresponds to the sprites you’d like to create. Ensure that the images you’re converting to sprites are PNGs and place them in your new directory. I’m creating flag sprites, so I’ve named my directory flags and placed three PNGs in the directory.

In a new SCSS file that I’ve called `flags.scss` (the name here is not important), the following three lines will, in order, import Compass’ sprite making tools, glob import the PNGs to be converted to sprites (notice that the path here does not include images/), and then generate the CSS for the sprites. Be mindful that the @include statement’s middle word needs to match the directory in the line before it.

@import "compass/utilities/sprites";
@import "flags/*.png";
@include all-flags-sprites;

This is a fairly simple process for generating sprites, but it has a few drawbacks/oddities:

  • The generated CSS does not include widths or heights for the sprites.
  • There is no shared class between the sprites; the background-image is applied to each class.

Generating Sprites with ImageMagick

ImageMagick can be used to create a spritesheet from the command line with the following commands:

convert *.png -append sprites.png # append vertically
convert *.png +append sprites.png # append horizontally

This will take all the PNG files selected by the glob and concatenate them into a single file, but will not create the corresponding stylesheet. If you use ImageMagick to create your sprites, you may want to read the section below on using Sprite Cow.

Using Sprite Cow with your Sprites

Sprite Cow is a hosted tool for generating a stylesheet corresponding to your sprites. It doesn’t make the sprite for you, it just helps you get numbers you need to use the sprite (the width, height, and background-position of individual parts of the sprite). It boasts 2x image compatibility and a simple interface for quickly designating which areas of the sprite make up each image to create CSS for. You just click the part you need and it gives you the CSS you need.

Generate Sprites with Spritepad

Spritepad is another hosted solution for creating sprites. With Spritepad, you upload individual images, position them however you’d like, and the CSS is updated in real time. When you’re done, download the image and copy the CSS over to your project.

Generate Sprites with SpriteMe

SpriteMe is a bookmarklet that generates a sprite based on what it finds on the current page. So essentially you’d develop without using sprites at all, then use this to sprite things together at the end. Here’s a workflow explaining how that would work.

Should my sprites be horizontal or vertical?

One option is neither. Compact them into a grid, making the smallest size, dimensionally that you can. The dimensional size of an image plays a role in how much memory the image will take up when being used, so the less the better. If you end up laying out your own sprite, Sprite Cow is a good tool to help with the CSS generation part.

If, for simplicity, you’re going to pick one or the other, one way to do that is to look at the largest width and the largest height of your image files. If the largest width is greater than the largest height, the sprite sheet should be arranged horizontally. If the largest height is greater than the largest width, vertically. If you’re using a generation tool, they will generally make this choice for you.

In some situations, it may actually make sense to lay out a sprite diagonally. This can make it possible to use a sprite in an area of unknown width and height, which is pretty cool.

Although another possible way to get around that is using a pseudo element.

Alternatives

There are a few alternatives to CSS sprites, but, as you might expect, they each have their own benefits and drawbacks.

Data URIs

Data URIs allow you to embed the image data directly into a stylesheet. This avoids additional HTTP requests for images, making it essentially the same thing as a sprite, without the fancy positioning.

Icon Fonts

Icont fonts are similar to sprites in that the achieve the same thing: combining multiple images into a single request.

SVGs

SVG images can be combined into a sprite as well and used as an icon system. It’s a slightly different approach though, utilizing the syntax and strengths of SVG. You may need to think about a fallback system though, as SVG doesn’t have as deep of browser support as CSS background-image (which essentially has no browser support issues at all).

Grunticon and Iconizr are possibilities for working with SVG sprites that help with the fallbacks.

#Using <img> and object-position

Robin Rendle has a great post on this clever technique here.

Examples

  • Mozilla Developer Network uses sprites to switch between different states when toggling their top level navigation.
  • Mailchimp uses sprites (background-image SVG) for their sidebar navigation in various states.

references: wikipedia, css-tricks

Refactoring CSS: The Three I’s

In a recent interview, I was asked about simple and/or replicable steps to take when refactoring CSS. The topics of legacy, Technical Debt, and refactoring are, for one reason or another, at the front of my mind at the moment, so I thought I would write up a short post on an approach to refactoring CSS (or any language) that I call The Three I’s: Identify, Isolate, Implement.

Identify

It’s all well and good knowing that ‘your CSS is a mess’, but which bits specifically? Which parts of your codebase are causing you problems right now? Which ones will be the quickest to refactor? Which parts will provide you with the most benefit once refactored? It is important to identify prime candidates for refactoring.

For example, the CSS for your nav might be cumbersome and hard to work with, but if the nav works correctly, is accessible, and you rarely have to edit the CSS for it, refactoring it will likely not provide you with much immediate value: we can probably afford to leave it as it is for a little while longer. However, your layout/grid system might be incredibly fragmented and inconsistent, it might have cross-browser issues, its responsiveness may have been bolted on as an afterthought, and of course it is probably used extensively and frequently. As a result, you might get a lot of value from tackling that first.

Have a clear idea of which parts of your project should be refactored, if at all.

Tip: Try to limit refactoring work to the scope of single features. It’s much safer to refactor a single feature than it is to refactor your entire naming convention, for example. For further detail on this, and much more, you can see my Refactoring CSS Without Losing Your Mind talk at a number of events throughout the rest of 2016.

Isolate

Once we have identified candidates for refactoring, we need to isolate them before and during working on them. Suppose we have decided to refactor our layout system first, we should rewrite this in isolation, outside of our project.

In order to do this, open a new jsFiddle, CodePen, etc. and begin work there. Do not refactor features back into a stale codebase, as doing so runs the risk of making use of legacy CSS that may itself be refactored in future. For example, we might be using a traditional reset in the current project, which may be replaced by Normalize.css in future—we don’t want to build our brand new layout system on top of a reset that will be removed in six months time.

Build the new/refactored version of your feature in complete isolation so that you know it is well encapsulated, and it’s not making use of any legacy.

Implement

The final step is to implement your refactored feature. Copy and paste the jsFiddle CSS into the relevant part of your project, and see what happens. 90% of the time, you’ll find that there are some problems: conflicts with existing CSS, naming collisions, existing styles leaking into your new code, etc.

We tackle these details at implementation stage, and we need to give careful consideration as to where we place the fixes. If the fix solves a problem with the layout system itself, it is usually best to place the fix in the layout system’s partial. If the fix addresses problems arising from conflicts with legacy code, it is often best to place it in a shame.css file. This keeps the legacy fix away from greenfield CSS, meaning it will be much easier to remove once we’ve refactored whatever legacy was causing the problem in the first place.

Move the refactored feature back into the project and tidy things up here.

In short:

Identify sensible candidates for refactoring: not all legacy is born equal.
Isolate the feature in order to rebuild it: do not lean on out of date code.
Implement the refactored feature into the project: do any cleanup work at this point, and in the right place(s).

reference: csswizardry

CSS On Scroll Animation Library

CSS On Scroll Animation Library

The Problem With Other Libraries

In my previous company we were using WOW.js (or other similar libraries) to animate elements on scroll. For simple projects it was quite nice, but on larger sites we wanted to have more control over what’s actually happening. In all of popular libraries, animations were completely handled by JavaScript by inserting inline CSS. Arghgh! Inline styles are evil. They are hard to control and override. Though, in some cases it’s ok to set them using JavaScript, it’s still much cleaner to just leave them where they belong and handle all CSS related things inside CSS file.

I decided to create a library that has a pure goal – detect position of elements and then add appropriate classes when they appear in viewport.

Controlling Animations Entirely in CSS

I wanted to split the responsibilities with my new library:

  • Have all the logic inside the JavaScript
  • Have all the animations in the CSS

This allows you to add your own animations easily, and do things like change them according to the viewport.

How AOS Works

The idea behind AOS is straightforward: watch all elements and their positions based on settings you provide them. Then add/remove the class aos-animate. Of course, in practice, it’s not always that easy, but the idea behind AOS is as simple as that. Every aspect of animation is handled by CSS.

Example Animations in CSS

The are lots of different animations ready to use out of the box, but creating new ones is simple also. Here’s an example:

[aos="fade"] {
  opacity: 0;
  transition-property: opacity;
}

[aos="fade"].aos-animate {
  opacity: 1;
}

You don’t have to worry about duration or delay. In the CSS, you only:

  • add styles for the attribute aos with the name of your animation
  • set the transition-property (by default this is all, so it’s more performant and more predictable if you narrow the transition to the intended properties)
  • add the post-transition properties on .aos-animate

Things like duration/delay/easing are set independently of the animation.

Example HTML

<div class="some-item" aos="fade">Example Element</div>

or with a different transition duration:

<div class="some-item" aos="fade" aos-duration="500">Example Element</div>

**Tip:** You can use data-aos instead of aos to make your HTML validate properly.

Live Demos

With different animations:

 

With anchor setting in use:

 

With anchor placement and different easing:

 

With simple custom animations:

 

Additional Features

  • anchor – Animate one element based on position of other element
  • anchor placement – Animate an element based on it’s position on the screen. It doesn’t have to animate only when it appears in viewport, but for example when bottom part of it hits middle of the screen
  • both way animations – By default elements animate while you scroll up and down, but you can force it to animate only once
  • easy disabling – Disable animations on mobile devices using predefined options like mobile, phone, tablet or with a custom condition/function
  • async aware – Recalculates positions of elements on DOM changes, so after loading something using Ajax, you don’t have to worry about anything (unless you support IE9, because it needs mutation observer)
  • no dependencies – This library is written in pure JS and doesn’t rely on any dependencies

reference: M. Sachnog

When to use @extend; when to use a mixin

There’s an old rule of thumb which states that mixins without arguments are bad—that mixins which just duplicate code with no difference between each instance are nasty. The truth is that the answer is a lot more nuanced than that.

Let’s take a look.

When to use @extend

Let me start by saying that I would generally advise never to use @extend at all. It is something of a Fool’s Gold: a feature with a lot of promise and twice as many caveats.

If you are definitely, completely set on using @extend:

  1. Please reconsider.
  2. Use the placeholder hack.
  3. Keep an eye on your output.

In theory, @extend is great, but, in practice, there is just too much that can go wrong. I have seen stylesheets more-than-double in size; I have seen source order get destroyed; and I have seen clients plough right through their 4095 selector budget. It is always better to err on the side of caution and omit any features or tools that have the potential to cause so much trouble with little or no tangible gain. Having to shard your stylesheets into less-than-4096-selector-groups as a result of misusing a productivity tool is very, very counterintuitive.

N.B. I feel I should add that this isn’t me hating on @extend per se; there’s just a lot to be aware of and you must remain vigilant if you are going to use it.

But, if you are going to use @extend, when should you?

It is important to realise that @extend creates relationships. Whenever you use@extend, you are transplanting a selector elsewhere in your stylesheet in order for it to share traits with other selectors that are also being transplanted. As a result, you are dictating that these selectors all share a relationship, and misusing @extend can create relationships around the wrong criterion. It would be like grouping your CD collection by the colour of their covers: doable, but not a useful relationship to create.

It is vital that you are forming that relationship around the right characteristics.

Quite often—and I have been guilty of it myself in the past—I have seen things like this (and let’s imagine that the ... denotes an omission of, say, 100 lines):

%brand-font {
    font-family: webfont, sans-serif;
    font-weight: 700;
}

...

h1 {
    @extend %brand-font;
    font-size: 2em;
}

...

.btn {
    @extend %brand-font;
    display: inline-block;
    padding: 1em;
}

...

.promo {
    @extend %brand-font;
    background-color: #BADA55;
    color: #fff;
}

...

.footer-message {
    @extend %brand-font;
    font-size: 0.75em;
}

Which, of course, gives us this:

h1, .btn, .promo, .footer-message {
    font-family: webfont, sans-serif;
    font-weight: 700;
}

...

h1 {
    font-size: 2em;
}

...

.btn {
    display: inline-block;
    padding: 1em;
}

...

.promo {
    background-color: #BADA55;
    color: #fff;
}

...

.footer-message {
    font-size: 0.75em;
}

The issue here is that I have forced a relationship between unrelated rules—that live hundreds of lines away from one another—based on shared traits that are purely coincidental. And not only have I forced an unusual relationship, but I now have a very unusual source order in which specificity is jumbled up. I am distributing selectors across my codebase for purely circumstantial reasons. This is not good news.

I have transplanted unrelated rulesets to hundreds of lines away from their source, in order to live with other rulesets, in the incorrect location, based on purely coincidental and circumstantial similarities. This is not a good way to use @extend. (In fact, this is probably a perfect use-case for an argument-less mixin. We’ll come back to that soon.)

Another case of an abused @extend looks a little like this:

%bold {
    font-weight: bold;
}

...

.header--home > .header__tagline {
    @extend %bold;
    color: #333;
    font-style: italic;
}

...

.btn--warning {
    @extend %bold;
    background-color: red;
    color: white;
}

...

.alert--error > .alert__text {
    @extend %bold;
    color: red;
}

This, as you would expect, gives us the following:

.header--home > .header__tagline,
.btn--warning,
.alert--error > .alert__text {
    font-weight: bold;
}

...

.header--home > .header__tagline {
    color: #333;
    font-style: italic;
}

...

.btn--warning {
    background-color: red;
    color: white;
}

...

.alert--error > .alert__text {
    color: red;
}

This weighs 299 bytes.

Oftentimes, the selectors you’re transplanting may be longer than the declarations you’re trying to avoid repeating.

If we were to actually just repeat the font-weight: bold; declaration n times—instead of trying to avoid repeating it at all—we’d actually achieve a smaller file size:264 bytes. This is just a very timid model, but it should help to illustrate the possibility for diminishing returns. @extending single declarations can often be counterproductive.

So, when do we use @extend?

We’d use @extend to share traits among explicitly related rulesets. A perfect example:

.btn,
%btn {
    display: inline-block;
    padding: 1em;
}

.btn-positive {
    @extend %btn;
    background-color: green;
    color: white;
}

.btn-negative {
    @extend %btn;
    background-color: red;
    color: white;
}

.btn-neutral {
    @extend %btn;
    background-color: lightgray;
    color: black;
}

Which results in:

.btn,
.btn-positive,
.btn-negative,
.btn-neutral {
    display: inline-block;
    padding: 1em;
}

.btn-positive {
    background-color: green;
    color: white;
}

.btn-negative {
    background-color: red;
    color: white;
}

.btn-neutral {
    background-color: lightgray;
    color: black;
}

This is a perfect use-case for @extend. These rulesets are inherently related; their shared traits are shared for a reason, not coincidentally. Further, we aren’t transplanting their selectors hundreds of lines away from their source, so our Specificity Graph stays nice and sane.

When to use a mixin

The mixins without arguments are bad rule is a well-meaning one, but unfortunately it’s just not as simple as that.

This rule stems from a slight misunderstanding of the DRY principle. DRY is a principle that aims for a Single Source of Truth within a project. DRY is about not repeatingYourself, it is not about completely avoiding repetition.

If you manually type a declaration 50 times in a project, you are repeating yourself: this is not DRY. If you can generate that declaration 50 times without having to manually repeat it, this is DRY: you are generating repetition without actually repeating yourself. This is quite a subtle but important distinction to be aware of. Repetition in a compiled system is not a bad thing: repetition in source is a bad thing.

The Single Source of Truth means that we can store the source of a repeated construct in one place and recycle and reuse it without ever actually duplicating it. Sure, a system might repeat it for us, but its source only ever exists once. This means we can change it once and that change will propagate everywhere; that there will be no duplication of that construct in our source code; that there is a Single Source of Truth. This is what we mean when we talk about DRY.

With this in mind, we can begin to realise that mixins without arguments can actually be very useful. Let’s go back to the %brand-font {} example from earlier on.

Let’s imagine we’re using a particular font in our project that must always be defined alongside a specific font-weight:

.foo {
    font-family: webfont, sans-serif;
    font-weight: 700;
}

...

.bar {
    font-family: webfont, sans-serif;
    font-weight: 700;
}

...

.baz {
    font-family: webfont, sans-serif;
    font-weight: 700;
}

It would get quite tedious to manually repeat those two declarations over and over in our codebase; we’d have to remember the number 700 as opposed to the more familiar regular or bold; and if we ever change the web font or its weight, we’d have to go through the project and change it everywhere.

We covered earlier that we should not force relationships by using @extend here, but what we probably should do is use a mixin:

@mixin webfont() {
    font-family: webfont, sans-serif;
    font-weight: 700;
}

...

.foo {
    @include webfont();
}

...

.bar {
    @include webfont();
}

...

.baz {
    @include webfont();
}

Yes, this will compile to repetition. No, we are not repeating ourselves. It is important to remember here that these are unrelated rulesets, so we did not ought to make them related. They are unrelated and just happen to have some shared traits, so this repetition is sensible, and is to be expected. We want to use those declarations inn places, so we make them appear in n places.

Argument-less mixins are great for just spitting out repeated groups of identical declarations whilst maintaining a Single Source of Truth. See it like a Sassy extension of your copy/paste clipboard: you’re just using it to paste out a few strings you’ve stored elsewhere earlier on. We have our Single Source of Truth, which means we can propagate changes to these declarations whilst only ever making one manual change. Very DRY.

It is also probably worth noting that Gzip favours repetition, so that will almost entirely negate the costs of the slight added filesize.

Of course, mixins are also really, really useful for generating dynamic values within repeated constructs: mixins with arguments. I don’t think anyone could say these are a bad idea: they’re DRY but also allow us to make on-the-fly modifications to our Single Source of Truth. For example:

@mixin truncate($width: 100%) {
    width: $width;
    max-width: 100%;
    display: block;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}

.foo {
    @include truncate(100px);
}

Spitting out the same declarations, but dynamically setting the value of width on a case-by-case basis.

This is the most common and widely agreed upon form of mixin, and I think we can all agree that these are a good idea.

tl;dr

Only use @extend when the rulesets that you are trying to DRY out are inherently and thematically related. Do not force relationships that do not exist: to do so will create unusual groupings in your project, as well as negatively impacting the source order of your code.

Use a mixin to either inject dynamic values into repeated constructs, or as a Sassy copy/paste which allows you to repeat the same group of declarations throughout your project whilst keeping a Single Source of Truth.

tl;dr;tl;dr

Use @extend for same-for-a-reason; use a mixin for same-just-because.

 

references: css wizardy

The Tragicomedy: CSS Color Names

The Tragicomedy: CSS Color Names

The “Named Colors” section of the CSS Color Module Level 4—the latest specification for color values and properties within the Cascading Style Sheets language—are 141 standard colors. Each has its own name, so beyond the essentials of “black” and “white” are shades like “papaya whip,” a warm orange pastel; “lemon chiffon,” a faint, milky yellow; and “burlywood,” which has likely made an appearance on a safari tour guide’s shorts.

At first glance, these names seem fluffy, and they bear connotations of sugary, whimsical romanticism. Where do such abstract names come from, and why are they a part of something as methodical as writing code?

The answer to these questions begins in 1980s Massachusetts. Originally, the colors were a product of the X Window System (X), a graphical user interface (GUI) released by MIT in 1984. In June of 1986, the first list of GUI colors, which was tuned to the DEC VT240 series terminal, shipped with the third release of X’s tenth version (X10R3). It comprised 69 basic shades, with 138 entries to account for different cases in the color names (e.g., lowercase with spacing like “dark red” versus camel case like “DarkRed”).

In 1988, X11R2 arrived with the addition of three colors, including the identical shades “gray” and “grey.” According to Austin-based developer Alex Sexton, discussing the colors at a JavaScript Conference last year, programmers at Hewlett-Packard couldn’t remember the proper spelling (which was originally with an ‘a’). Including two names, it was thought, would prevent errors.

The most substantial release, created by Paul Raveling, came in 1989 with X11R4. This update heralded a slew of light neutral tones, and it was a response to complaints from Raveling’s coworkers about color fidelity. (In the ‘80s, colors could vary dramatically from monitor to monitor, depending on the machine vendor. As if to illustrate this, a particularly baffled employee exclaimed, “That’s Wheat???!!!” upon the sight of the hue in the previous text file.) In this version, programmers were introduced to the aforementioned “papaya whip” and “lemon chiffon,” as well as other loftily-named hues like “blanched almond” and “peach puff.”

Raveling drew these names from an unsurprising source: the (now-defunct) paint company Sinclair Paints. It was an arbitrary move; after failing to receive sanctions from the American National Standards Institute (ANSI), which issued standards for Web color properties, Raveling decided to take matters into his own hands. He calibrated the colors for his own HP monitor. “Nuts to ANSI & ‘ANSI standards,’” he complained.

Later that year, X11 gained a set of bolder colors thanks to another programmer, John C. Thomas. Just as Raveling’s update tweaked shades to assuage user confusion, Thomas’s addressed the following written objection from coworker Bruce Schuchardt in 1989:

“[I] am still shocked and horrified by the default colors in the rgb database. The ‘pink’ color in particular looks like the flesh-tone of someone who has been puking for several hours and would really rather get a bullet in the head than go on living.”

Thomas agreed. Frustrated with inconsistent displays, he started to find it futile to standardize color names. In response, he stated in an e-mail that he “sat down one evening with the handiest standard of subjective color names, a box of 72 Crayola crayons.” That birthed “aquamarine,” “orchid,” and “salmon,” to name a few.

By 2001, the World Wide Web Consortium (W3C) published the first working draft of the CSS 3 Color Module that would include the colors. In light of evolving technologies, the colors had fallen out of use, but the W3C claimed the goal was to “codify current practices.” Every browser supported the colors at this point, consequently, the W3C had been using them in compatibility tests. Incorporating the colors into CSS, then, would prevent sites from breaking.

“It was like a backwards-compatibility thing. They thought, ‘We’ve accidentally been doing this, so we might as well just not break it,’” Sexton told Ars.

Backlash ensued. The color database had been subjected to the whims of so many different programmers that it became deeply disorganized, leading some to argue it had no place in CSS. Critics attacked its naming scheme: “dark gray” was lighter than “gray”; there was a “medium violet red” but no “violet red”; “light goldenrod yellow” had no corresponding “goldenrod yellow.” In total 17 colors had dark versions, but only 13 had light ones. Color distribution was also uneven, skewing toward reds and greens and away from blues.

Perhaps the most vehement denunciation comes from a 2002 e-mail written by programmer Steven Pemberton: “The X11 colour names are an abomination that should have been stifled at birth, and adding them to CSS is a blemish on the otherwise excellent design of CSS. To say that the X11 colour set and their names have been ‘designed’ is an insult to the word ‘design.’ It is just a mess.”

Another point of contention was cultural exclusion. Some programmers took umbrage at the region-centric nature of names like “dodger blue” and the potential racial undertones of “navajo white” (from Sinclair Paints) and “indian red” (from Crayola, though the crayon has since been renamed in response to the same concerns). Others considered the English-only names alienating.

“I’m not a native English speaker. Imagine my reaction the first time I saw the ‘gainsboro’ color  or ‘papaya whip,’” Daniel Glazman, co-chairman of the CSS Working Group, told Ars.

Ostensibly, these repercussions could have been prevented. In the ‘80s, X system programmers had the option to identify colors the way many developers do today: with a hexadecimal value (AKA hex value, e.g., #FFFF00) or an RGB color code (e.g., 255,255,0). These options allow a greater degree of choice and precision, and they’re based on schematic, objective, globally legible systems. Why weren’t they used in the first place?

“It was a recognition that almost nobody likes using the numeric values. People don’t think in terms of F5B as a particular shade of color. Using a name is more natural,” said Jim Fulton, a student at MIT at the time of X’s creation and manager of Raveling’s and Thomas’s files. However, he conceded, “Not every idea works out well.”

Do you need to update some of your tools to add more color? I would suggest the following from Adobe Creative Cloud:

In 2014, however, an unexpected event cast the color list in a more favorable light: a new shade. “Rebecca purple,” was introduced to honor the life of Rebecca Meyer, the daughter of Eric Meyer, a respected programmer and CSS writer. Rebecca died of brain cancer at the age of six; the hue (#663399) was chosen to reflect her favorite color. (A few developers opposed the addition, maintaining that a set of standards was no place for an emotional tribute. They were dismissed as curmudgeons.)

Still, the general consensus is that these colors’ utility is minimal; they’re best reserved as placeholders (it’s easier to type “tomato” than “#FF6347” when you need a color quickly), for beginner-level design projects, or as the butt of a joke.

“I view it with amusement that the colors seem to have migrated into CSS. I just laugh at it,” Fulton told Ars. “I think if someone were to go and crawl over the top 100 or top 1,000 sites and take a look at how various colors are specified, I’m willing to bet you’d still find close to zero percent using color names beyond ‘white’ or ‘black.’”

“If I’m doing an example to show people how to use an editor or a framework, I use hex values like #C0FFEE or #BADA55. It’s about as useful to use #C0FFEE as it is to use ‘papaya whip,’” Sexton added.

Should the colors have been left without standard names then, sparing the development community from a series of angry e-mails and micro-controversies? According to Fulton, probably. Then again, as programmers navigated the uncharted territory of color-displaying GUIs in the ‘80s, it was only natural to experiment any way they knew how.

“At the time, we were dealing with, in some ways, the very beginnings of the graphical home-computer industry,” he said. “For color devices especially, this was the very beginning.”

references: eric meyer

Using IDs with CSS

If we want to keep specificity low, which we do, we have one really quick-win, simple, easy-to-follow rule that we can employ to help us: avoid using IDs in CSS.

Not only are IDs inherently non-reusable, they are also vastly more specific than any other selector, and therefore become specificity anomalies. Where the rest of your selectors are relatively low specificity, your ID-based selectors are, comparatively, much, much higher.

In fact, to highlight the severity of this difference, see how one thousand chained classes cannot override the specificity of a single ID: jsfiddle.net/0yb7rque. (Please note that in Firefox you may see the text rendering in blue: this is a known bug, and an ID will be overridden by 256 chained classes.)

N.B. It is still perfectly okay to use IDs in HTML and JavaScript; it is only in CSS that they prove troublesome.

It is often suggested that developers who choose not to use IDs in CSS merely don’t understand how specificity works. This is as incorrect as it is offensive: no matter how experienced a developer you are, this behaviour cannot be circumvented; no amount of knowledge will make an ID less specific.

Opting into this way of working only introduces the chance of problems occurring further down the line, and—particularly when working at scale—all efforts should be made to avoid the potential for problems to arise. In a sentence:

Minimize the use of IDs.