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

Advertisements
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:

Image File Size Dimensions
canada.png 1.95KB 256 x 128
usa.png 3.74KB 256 x 135
mexico.png 8.69KB 256 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

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