CSS Tricks

CSS Tricks: The Ultimate guide for advanced CSS hacks

If you have ever considered learning some advanced CSS tricks, than this guide is a great place start. It covers the following CSS topics;

  • Animate CSS
  • Refactoring CSS Code
  • Native CSS3 Animations
  • Using Color Gradients in CSS3
  • An Overview of CSS Positioning
  • An overview of CSS Selectors
  • Understanding specificity in CSS
  • Using WOW.js and Animate.css for Scroll-Triggered Animations
  • Introduction to CSS flexbox & Advanced CSS Selectors

What is Animate.CSS [Tutorial]

This section explains how getting started with Animate.css better supports web developers in creating creative and function animate designs through simple and efficient programming. To upgrade web content and improve application designs, Getting Started with Animate.css [Tutorial] is a great way to make unique content. Developers gain an advantage over other competing sites with creative and different features, faster and better quality content, and better cross-browser compatibility when sharing web site content across the digital environment. The Animate.CSS library extension provides the tools, simplicity, and flexibility for all web and mobile app development services.

CSS animation is an extension of Cascading Style Sheets (CSS) with different animation features. The module embeds a library of designs for websites an offers users with convenience, creativity, and professional web applications. Web developers Getting Started with Animate.css [Tutorial]  apply animation designs, edit CSS sequences, and improve website design through the Cascading Style Sheet extension. The extension simplifies developer interaction when implementing animation designs with straightforward configurations to specific HTML elements that require less processing and memory usage from Flash or JavaScript.

Advantages

Without a doubt, Animate.CSS gains popularity from the developer community for simplicity and compatibility. Primarily, Animate.CSS has simple and ready to use style sheet scripts that copy and paste into developer website documents for high developer convenience. Also, the module is built to prevent users from settling for generic GIFS or Flash images that limit developer creativity and require additional steps that slow down project development completion times. Additionally, there are are a lot of shorthand animation design style scripts for animation properties when Getting Started with Animate.css. Importantly, the Cascading Styles Sheet (CSS) Animate.CSS program includes advanced keyframes extensions that better equip developers with design customization developer tools needed for creative and functional animated designs. Along with an easy to use the module, Animate also proves compatible for additional upgrades or improvements with Javascript.

How do Animations Work in Animate.CSS

CSS animate is a unique library module built from a simple and effective design. To explain, Animate.CSS includes two main components for styling websites. The first component styles and stores information for CSS animations. However, the second component uses “keyframes” to signal web developers the beginning and end of sequences for animation designs. Also, this component uses advanced transition points to allow better animation configuration.

Getting Started with Animate.css [Tutorial]

Creating an Animation

CSS animations include primary and sub-property components. Usually, web developers getting started with Animate.css  using Animate.CSS style-specific script elements and include additional designing styles for animation properties. More specifically, properties work between different stye functions to equip websites with functional and simple animations. Animation properties include wide criteria of style elements such as animation-name, duration, timing, and delays. Other forms include animation count, direction, fill, and play. Fortunately, the library module enables web designers to apply these properties to website animations with simple text sequences, rather than formatting and testing numerous codes with functional uncertainty.

Keyframes

Through the.CSS Animate extension, users work with “keyframes” to create animation with component elements.  For the benefit of users, the “keyframes” are setup through Cascading Style Sheets to offer users gradual editing capabilities to CSS style sets while allowing web developers to focus on important animation features. To elaborate, the “keystones” help users perform configurations within timing, duration, and in-depth detailing elements within a different design sequence.

Keyframes At-rule

Additionally, the display of the animations requires users to operate “keyframes at-rule” to better connect with component elements. For more specific property configurations, the extension corrects animation values between design “keyframes.” For identification purposes, web developers value “keyframes at-rule” to edit multiple names within sequences and locate elements that do not have value to the CSS style set. Furthermore, the “keyframes at-rule” expands editing capabilities for web developers with useful code indicators for animations to better render elements during design styles.

Annimate.CSS Transform

Equally important, Cascading Style Sheets (CSS) Animate.CSS features offer  “transforming” properties for better element editing. Elements not compatible with CSS designs alter with the transform tool. Beneficially, developers using transform tools such as scale, rotate, skew, and translate will configure elements to better design on web applications. Transform properties, either 2d or 3d, provide users with additional designing creativity and functionality when creating websites.

Scale

With scale, users of Animate.CSS adjust the dimensions of designs to better fit web content. The specific CSS transform function corrects width and heights of elements to better scale content on web apps. By default, scale values start with an attribute of one, which adjusts to a value greater or less than one form more or less scalability for elements. Put simply, the attributes on CSS enable proportionate corrections when handling scaling configurations to element and content design.

Skew

To continue, the transform tools on Animate.CSS consists of a skew function for web developers. The design of element properties aligns with a horizontal and vertical axis on web apps which may be skew. Typically, the skew functions include “x” and “y” values to assist developers to distort elements on the axis.

Translate

Another transform feature is CSS translate. Similarly, the translate function also shares “x” and “y” values to assist better design functionality for developers. Unlike the CSS skew function, they translate tool allows users to position a particular element within both the horizontal and vertical axis.

Rotate

In addition, developers getting started with Animate.css use the transform tool also includes a rotate function for elements. With ease, users may adjust the angle of an element in any direction. The rotation values are positive when rotating content clockwise and drop off to negative values when adjusting an element counter-clockwise.

Matrix

Finally, CSS transform features include matrix functions for elements. Especially useful for developers, the matrix tool joins 2d configurations onto a single element for universal editing applications.

Getting Started with Animate.css [Tutorial]
Just-add-water CSS Animation

The Animate.CSS system refers to “Just-Add-Water.” The module classifies as a “cross-browser” animations source which indicates its user-friendliness and simple design for new or established web developers.

Installation

To begin, the administrators require installation of the Just Add Water Cascading Style Sheets Animation program. First, installation occurs via NPM. To define, the Node Package Manager collaborates with JavaScript script, which shares the design of Animate.CSS. By default, the programming language operates with Node.JS as a stable premise for web development. Next, users use this code “$ Node Package Manager install animate.css –save,” to install the program.

Alternatively, the sequence follows “$ yarn add animate.css.” To further explain, a yarn installation also assists administrators with project installations. Ordinarily, “Yarn” associates installations with dependencies that use codes or another decency for installation. Unlike, the Node Packaging Manager (npm) install method, the “yarn” alternative does not apply a “–save” or “–sav-dev” when adding new programs. In-depth, a dependency can not operate unless with support from another more prominent program. The combination of the module and installation extensions collaborate with innovative new library models.

Using Animate.CSS [Tutorial]

On the Animate.CSS website, open-source codes are available for web developers. The user may select the Download Animate.css to access different Cascading Style Sheet animation text. The list includes a wide variety of design styles and may apply directly to the user website. Additionally, the download code is another method for getting started with Animate.Css.

Getting started on Animate.CSS on Websites

Applying the Cascading Style Sheets (CSS) stylesheets onto the developer website is easy, fast, and effective. However, text implementation requires user attention to detail. First, the Cascading Style Sheets (CSS) animate.CSS stylesheet must be correctly placed within the developer’s document “<head>.” Next, the administrator applies the “animated” stylesheet class to an element within the web application document. Also, the animated script follows CSS names to perform specific animation functions for the element. Alternatively, users may switch over to other versions, like CDNJS, as another host for Annimate.CSS element configurations. The format is shown below:

Getting Started with Animate.css [Tutorial]

Animations on Animate.CSS

Web designers getting started with Animate.css value simple and quality animation that differentiates content on web applications. The animation stylesheets provided on Animate.CSS includes an abundance of Cascading Style Sheet (CSS) animation styles that customize document elements. Moreover, to create an animation design to an element, the developer must input the “animated” tag. The class embeds within a document element and requires additional instruction to better define content attributes. Commonly, developers rely on an active element with a feature set to “infinite” to enable multiple cycles of animation designs within a web site. Also highly regarded, the duration constraints on animations, along with delays and user animation interaction are available within the Animate.CSS style sheets list.

Getting Started with Animate.css [Tutorial]
Shown below are animation classes for web developers getting started with Animate.css [Tutorial] to implement into web application documents.

Start Timing Animations

For the most part, web developers getting started with Annimate.CSS seek animation designs to improve the content on web sites. Reasonably, the animation should have the ability to perform as a method to attract site visitors to particular information on sites. Therefore, developers should understand how to configure elements in regard to animation delays, speed, and timing.

Delay

Presently, Animate.CSS assists developers with delay features with a particular stylesheet. For example, a stylesheet with a delay function might appear like this: “<div class=”animated bounce delay-2s”>Example</div>.” In this scenario, a delay of two seconds occurs for an element that has a bounce animate class attached. Delay classes identify as “delay” and can alter delay functions from one to five seconds. Further delay periods are acceptable if users add Cascading Style Sheet (CSS) texts especially the code.

Speed

Additionally, element designs on Annimate.CSS have speed time values. The developer may correct the speed of an animation using a specific stylesheet for the class. For instance, an animation time sequence may look like this: “<div class=”animate bounce faster”>Example</div>.” Moreover, the developer enables the animate element to bounce and creates a speed function of “faster.” Additionally, class names may refer to as “slow,” “slower,” “fast,” and “faster.” Along with class names, speed times like “2 seconds,” “3 seconds,” “800 milliseconds,” and “500 milliseconds” address the rate of the elements function. By default, the element rates set to a standard value of one second. Users, with additional extensions, may alter timings by manual text editing within the Cascading Style Sheets (CSS) Annimate.CSS stylesheets.

Start Custom Builds

Previously mentioned, developers can manually adjust the Animate.CSS stylesheets to develop new animations separate from the standard defaults. Another source, such as “gulp.js,” is Animate.CSS compatible and offers easy to set up custom animation builds. More specifically, the cross-browser platform is an automation program for task development. For web developers and programmers, The Gulp extension analyzes and organizes a variety of pipe-driven files to support plug-ins on user servers. In this case, Gulp interacts with dependencies for the creation of personalized animation builds and functions.

As an example, the initial phase calls developers to input the stylesheet script “$ cd path/to/animate.css/.” Once again, the administrator addresses the document with a “$ npm install.” After, web developers will join the builds into the “NPX Gulp” packaging program. As a plus, the packaging within Gulp is adjustable to include animate design styles to fit the web content. Users would edit this package with an “animate-config.json” script to select and choose appropriate builds. Selecting through the build options with values of “true” and “false” determine which builds are added or removed from the NPX Gulp list.

Animate.CSS with Javascript

With Javascript, the Animate.CSS library module enables users with additional features for designing web applications. The features include more specific animation functions with specific directional instructions, animation timing signals, adding and removal animation keys, and post animation effects. Also, Javascript offers better cross-browser functionality for the Animate.CSS extension and allows users more flexibility on which decelerations perform best for user software.

Summary

In summary, Animate.css is a cross-browser library module with simple and effective Cascading Style Sheet (CSS) programming. The design encourages developer creativity with compatibility for alternative dependencies and includes numerous animate design features. Along with different versions of design stylesheets, animation behavior also changes through programmer text interaction. Web application developers, with the support of Annimate.CSS, create more responsive websites with quality animations that are easy to maintain and provide unique website interaction.

Refactoring CSS Code

Refactoring CSS Code

Writing good code is about more than just getting the results you want on a webpage. Good code should be as efficient and concise as possible. While there are often numerous ways to achieve the same results, the most succinct and simple method is, with few exceptions, the ideal choice.

There are two major benefits of writing good, clean code. Firstly, it can dramatically improve site speed and performance. The smaller your file is (and the fewer external requests you are sending) the less time it will take for your website to load in the browser. Secondly, writing good code has the invaluable benefit of making it easier to maintain. Whether you are coding a project on your own or with other developers involved, the more lean your code is (ideally with good documentation), the less it’s going to be a headache for anyone having to revisit the codebase.

Best practices for writing good code are often applicable to all programming languages, although this post will specifically be tailored to improving the CSS on your website.

Remove unnecessary HTTP Requests

Many times in the process of developing a website, you may end up with multiple external files and dependencies linked to from your HTML document or CSS files. You may try out multiple different fonts or CSS frameworks, hosted on an external CDN. Each one of these dependencies represents an HTTP request your site is making each time it is loaded in the browser. This puts a great strain on site load time, and all of these requests add up pretty quickly.

If you added a bunch of external font files to your project, but are currently only referencing 1 or 2 in your CSS file, go through and remove any of these linked dependencies from the <head> of your HTML document.

Are you only using a CSS framework for just a few lines of code? Consider copying and pasting these lines to your main .css stylesheet, and remove the link to the original CSS framework code.

Simplify & Consolidate CSS Rules

While writing CSS, you may end up repeatedly writing the same rules for various different elements and selectors. In computer programming, the oft-repeated concept of “DRY” (Don’t Repeat Yourself) applies to CSS as well. Anytime you find yourself writing the same CSS rules for different selectors, find a way to consolidate them.

For example, instead of writing:

p {
  font-size: 14px;
  margin: 0 auto;
  display: inline-block;
}
​
h1 {
  margin: 0 auto;
}
​
img {
  display: inline-block;
  margin: 0 auto;
}

 

Consider writing:

p,
h1,
img {
  margin: 0 auto;
}
​
p {
  font-size: 14px;
}
​
p, 
img {
  display: inline-block;
}

 

Or even better:

/* applied to p, h1, and img elements */
.def-margin {
  margin: 0 auto;
}
​
/* applied to p element */
.def-fs {
  font-size: 14px;
}
​
/* applied to p and img elements */
.d-ib {
  display: inline-block;
}

 

While this may not seem like a big difference (at least in terms of lines of code), the total count of characters has been significantly reduced, which will have an impact on page load times. Additionally, it consolidates elements and selectors that are utilizing the same styles, making it clearer to see what common styles are being applied to different elements.

Refactoring CSS Code

 Reasses your ID & Class values

It’s often tempting to assign an aspect of style presentation as your class or ID values, but this is far from ideal. For example, for an error message, it can often seem to make sense to use red as the class or ID value, like so:

<div class="red">This is an error message</div>

 

But what happens if you change the color or other styles of this class? This class will no longer have a direct relation to its content or presentation, and will most likely cause confusion. A better choice in this situation would be to use a class value that explains its function, rather than its stylistic presentation:

<div class="error">This is an error message</div>

 

It’s always a good idea to use class and ID values that describe the content or function of that element, rather than any stylistic descriptions. Style can change many times throughout the process of creating a site, but using descriptors for functions will make the code much more readable and easy to maintain.

Reasses your selector choices

There are often many different ways of selecting an element, but there are often more efficient ways than others. While it is possible to nest selectors inside of each other in order to get to a specific element, if you find yourself having to go too many levels in, it might be best to reassess if a class or ID value would function better.

Check for redundancies

In the process of styling your webpage, you may try out a variety of different colors, for example many shades of the same color. It’s easy to leave these different rule sets in your code, without deciding on a definitive single color. A good tool to use to check for these types of redundancies is cssstats.com.

Not only will this simplify your code, it will also make your overal design much more consistent, rather than having 40 different shades of a color on the site.

Minify your CSS files

Once your CSS files are fully ready for production and deployment to a live server, it’s a good idea to minify them for best performance. A minifier will remove all white space from your source code, significantly reducing the file size. Since source code does not rely on white space for its functionality (only its readability), this will have no negative affect on how your site runs.

There are many free tools for minifying CSS (and JS files). One option is cssminifier.com.

Consolidate your CSS files

As was briefly touched on in the last post, it is a good idea to consolidate your resources as much as possible. While there is a good argument for keeping CSS modular during the development stage (such as keeping layout rules in one CSS file, color options in another, etc.) — ultimately you will want to consolidate all of these CSS rules into a single file for best performance.

Native CSS3 Animations

Native CSS3 Animations

Although popular libraries like Animate.css make it easy to add CSS animations to your project, they are largely comprised of common motions such as “bounce”, “shake” and other stock movements that can feel rather stale when overused. By taking advantage of the animation properties built in to CSS, you can create much more complex and customized animations far beyond just motion. CSS animations can effect element color, size, position or any other property available in the CSS3 specification. This post will give an introduction to getting started with the native CSS3 properties and some examples of possible uses for them.

Adding animation to an element

To give an HTML element animation, the first two steps are to declare a name for the animation and a duration. This is done with the animation-name and animation-duration properties:

#myAnimation {
    animation-name: color-change;
    animation-duration: 5s;
}

 

animation-duration can accept any value in seconds or milliseconds (declared using s or ms after an integer).

Creating the animation

Once you have declared a name and duration, it’s time to build the animation. This is done using the @keyframes rule, followed by the animation name:

@keyframes color-change {
    
}

 

Inside of the @keyframes rule will be a rule for each “frame” of the animation, designated by a percentage value from 0% to 100%. 0% is the very beginning of the animation, 100% being the end, with any percentage values possible in between. This can be thought of much like a video or flipbook, where each page of the book is a unique frame that when combined, creates motion:

@keyframes color-change {
    0% {
        background-color: black;
    }  
    50% {
        background-color: gray;
    }
    100% {
        background-color: white;
    }
}

 

In the example above, the color-change animation will change the background-color of the #myAnimation element from black at 0%, to gray at 50% then finally to white at 100%.

The power of using custom animations, though, is that you can change absolutely any CSS properties, with any level of incremental change in frames. A good example of this is for :hover pseudo-classes. CSS :hover states are often used to apply a color or minor stylistic change when an element is hovered over with a mouse, but animations allow these changes to be much more detailed.

button:hover {
    animation-name: button-anim;
    animation-duration: 5s;
    animation-fill-mode: forwards;
}
@keyframes button-anim {
    0% {
        background-color: blue;
    }
    50% {
        transform: scale(2.1);
        background-color: dodgerblue;
    }
    75% {
        transform: scale(2.5);
        background-color: white;
    }
    100% {
        transform: scale(1.5);
        background-color: blue;
    }
}

 

In the example above the button-anim animation effects any button element when it’s hovered over. Its background-color changes in four equal steps over a duration of 5 seconds, with the size of the element itself changing in discreet, unique steps as well (original, to 2.1x, to 2.5x, to then 1.5x the original).

One additional property included in the example above is the animation-fill-mode property. This property can be used to indicate how styles should be applied before (and after) the duration of the animation has completed. Using animation-fill-mode: forwards indicates that the styles in the last frame of the animation (those in the 100% rule) will remain applied. Without the addition of the animation-fill-mode property, the styles of button would revert back to their original state after the animation had completed.

Conclusion

CSS animations can be very complex and detailed, with up to 100 distinct frames able to be specified. Considering this feature is available natively in vanilla CSS, they are a great way to add visual interest and complexity to a web project, well-supported in all modern browsers.

Using Color Gradients in CSS3

Using Color Gradients in CSS3

Since the introduction of CSS3, it has been possible to use color gradients as a background, with 2 or more colors gradually fading into each other. Previously, creating gradients had to be done using Photoshop or other image editing software. Used effectively, this is a great way to add interest and even texture to webpage designs, beyond just static background colors. While legacy versions of Internet Explorer do not support this feature, you can safely add them to a project, as all modern browsers do support it. This post will take a look at using gradient backgrounds, and the available customization options.

Basic Linear Gradients

To set the background of an element (whether it be the body, a div, or other element), the background property is used, typically with a color value:

body {
  background: #fffbed;
}

 

To use a linear gradient instead of a solid color, include at least two colors (using either hex, rgb, hsl, or named colors values), separated by commas, inside of the linear-gradient() value:

body {
  background: linear-gradient(#fffbed, #45add3);
}

Basic Linear Gradients

Vendor prefixes

Since different browsers handle the linear-gradient value differently, it is highly recommended to use vendor prefixes along with it. This will ensure that the value is understood by Safari, Firefox, Chrome, and Opera. To use vendor prefixes, simply add 2 additional background rules with the linear-gradient value prefixed with -webkit- and -moz-. They should also appear before the regular rule without any vendor prefix:

body {
  background: -webkit-linear-gradient(#fffbed, #45add3);
  background:    -moz-linear-gradient(#fffbed, #45add3);
  background:         linear-gradient(#fffbed, #45add3);
}

 

It’s a bit extra typing, but it ensures that your gradients will be supported across all major browsers.

Controlling direction

By default, gradients will transition from top to bottom, with the first color included in the linear-gradient value being the top color.

You can change the direction of the gradient, though, by adding some direction keywords before the colors (i.e. to top, to bottom, to right, to left, to right top, etc.)

body {
  background: linear-gradient(to right bottom, #fffbed, #45add3);
}

 

When setting the direction to a corner, either the x- or y- axis can be stated first (i.e. to right bottom and to bottom right are the same).

Multiple colors

You can utilize more than two colors in a gradient, simply by comma separating them:

body {
    background: linear-gradient(#eaecee, #abebc6, #45add3);  
}

or

body {
  background: linear-gradient(#eaecee, #ebdef0, #f4f6f7, #abebc6, #4eb39d, #45add3);
}

 

Color Stops

Sometimes you will want to control where a certain color begins, allowing for certain colors to take up more space or have a wider space to transition. To add these “color stops”, just add a percentage value after a given color, to designate where that color should begin:

body {
    background: linear-gradient(#eaecee, #abebc6 30%, #45add3 %80);
}

 

This is great for having finer control over your transitions, and can be used for interesting effects.

Radial Gradients

One available variation on linear gradients are radial gradients. Radial gradients will transition from the center of the element, transitioning outward like a circle. They use almost the exact same syntax as linear gradients, just with the radial-gradient value instead:

body {
  background: radial-gradient(#eaecee, #45add3);
}

CSS3 Color Gradients

 

An Overview of CSS Positioning

One of the most important properties in CSS to understand is the position property. While much can be done to layout elements on a page without explicitly changing values for the position property, most advanced layout issues will require knowing the different values available for this property. This blog post will take a look at the four main values for position, and the instances in which you might use each of them.

Position Static

static is the default value of position, meaning that for any element you don’t explictly set any value for position, it will be static by default. Elements with a position of static will not accept any box offset properties, such as margin or padding .

In the example below, each div will be stacked on top of each other, since each is a block-level element:

<div class="container">
    <div class="unit unit-1">Unit 1</div>
    <div class="unit unit-2">Unit 2</div>
    <div class="unit unit-3">Unit 3</div>
    <div class="unit unit-4">Unit 4</div>
</div>

 

body {
  font-family: Helvetica;
  color: white;
}
.container {
  background-color: #fffbed;
}
.unit {
  background-color: #337e7e;
  height: 80px;
  width: 80px;
  text-align: center;
  line-height: 80px;
  border: #696969 2px solid;
}

 

CSS Positioning

Position Relative

Elements with a position of relative are very similar to the value of static, although with one major difference: they can accept box offset properties of top, right, bottom, and left.

In the case of an element with a position of relative, these offset properties set the distance from the elements normal position. In other words, if you were to set an element with a position of relative to have a top value of 10px, the element would appear 10px lower than where it would normally appear if its position were static.

Elements with a position of relative stay within the normal “flow” of elements, the box offset properties simply shifting the elements from its normal flow:

<div class="container">
    <div class="unit unit-1">Unit 1</div>
    <div class="unit unit-2">Unit 2</div>
    <div class="unit unit-3">Unit 3</div>
    <div class="unit unit-4">Unit 4</div>
</div>

 

body {
  font-family: Helvetica;
  color: white;
}
.container {
  background-color: #fffbed;
}
.unit {
  background-color: #337e7e;
  height: 80px;
  width: 80px;
  text-align: center;
  line-height: 80px;
  border: #696969 2px solid;
  position: relative;
}
.unit-1 {
  top: 10px;
}
.unit-2 {
  right: 30px;
}
.unit-3 {
  left: 20px;
}
.unit-4 {
  bottom: -30px;
  right: 40px;
}

 

An Overview of CSS Positioning

Position Absolute

Elements with a position of absolute also accept box offset properties, although they are removed from the normal flow of elements. Using box offset properties on an absolute positioned element will position that element in direct relation to its parent element.

Taking the exact same CSS as the position: relative; example above, but simply changing the position to absolute will result in entirely different positioning of the individual elements:

<div class="container">
    <div class="unit unit-1">Unit 1</div>
    <div class="unit unit-2">Unit 2</div>
    <div class="unit unit-3">Unit 3</div>
    <div class="unit unit-4">Unit 4</div>
</div>

 

body {
  font-family: Helvetica;
  color: white;
}
.container {
  background-color: #fffbed;
}
.unit {
  background-color: #337e7e;
  height: 80px;
  width: 80px;
  text-align: center;
  line-height: 80px;
  border: #696969 2px solid;
  position: absolute;
}
.unit-1 {
  top: 10px;
}
.unit-2 {
  right: 30px;
}
.unit-3 {
  left: 20px;
}
.unit-4 {
  bottom: -30px;
  right: 40px;
}

 

CSS Positioning

Position Fixed

An element with a position of fixed is very similar to position: relative;, although the position is relative to the browser viewport, rather than any parent element. Additionally, the element will not scroll with the page, remaining “fixed” and always visible, regardless of where the user is at on the page. This is often used to “fix” headers and footers to the page, in order to always remain visible.

An overview of CSS Selectors

An overview of CSS Selectors

In web development there are often numerous ways to achieve the same result. A key to writing good code (regardless of the language), is using the most efficient method possible, writing as little code as necessary and keeping the codebase to the absolute minimum. This will result in both faster page load times, as well as clarity in the source code for yourself and other developers. In writing CSS, it is important to know how to select the elements you want to target, and the best method to do so. This section will take a look at some of the most common CSS selectors, and the best instances in which to use each of them.

Type Selectors

For every HTML element, there is a corresponding selector for that element type. Whether it be a div, p, img or any other HTML element, the corresponding CSS selector is exactly the same, minus the angle brackets used in the tag:

p {
  color: black;
}
div {
  display: inline: block;
}
img {
  width: 200px;
}

 

Type selectors are ideal when you want to target every instance of a given element type and apply the same styles for all of them.

Class Selectors

Class selectors utilize a class name associated with specific elements. This selector is ideal when you want to apply certain styles to a variety of a different elements, regardless of the element type. For example, you may have a class of .responsive applied to a p, div and img element:

<p class="responsive">This paragraph is responsive</p>
<div class="responsive">
    A responsive div
</div>
<img class="responsive" src="http://google.com/my-responsive-img.jpg">

 

The following CSS code block will target all of these elements with the same class:

.responsive {
  width: 80%;
  margin: 0 auto;
}

 

Class selectors are always designated in a stylesheet using a period (.) before the class name.

ID Selectors

ID selectors are similar to class selectors, although they can only be applied to a single element in a given HTML document. This is useful when you only want to target a single element:

<p id="myParagraph">This is a paragraph with unique styles</p>
#myParagraph {
  color: green:
  width: 200px;
  float: left;
  display: inline-block;
}

 

ID selectors are always designated in a stylesheet using the pound or hash sign (#) before the ID name.

Universal Selector

The universal selector will target every single element in an HTML document. This is often used for CSS resets, such as removing default margin, padding and other styles from all elements:

* {
  margin: 0;
  padding: 0;
}

 

The universal selector is designated using the asterisk (*).

:hover

Another common selector (and one of the many CSS “pseudo-classes”) is :hover. Adding this pseudo-class to any selector will target the element’s hover state. This means that these styles will only be applied when a user hovers over that element with their mouse:

a:hover {
  text-decoration: underline;
  color: purple;
}

 

:hover is often used for links or any element you want to highlight when the user is hovering over it. This pseudo-class works well for laptop and desktop users, although has no real use for mobile devices, due to the lack of a mouse cursor.

Understanding specificity in CSS

Understanding specificity in CSS

In the process of writing CSS code, you will invariably run into situations where the code you just wrote seems to have absolutely no effect at all on the page. This can be frustrating, confusing and difficult to troubleshoot without the aid of something like Chrome Developer Tools. However, having a better understanding of how specificity and the cascade in CSS works can go a long way in mitigating these issues altogether. This section will aim to point out some of the main issues that typically come up when trying to determine which piece of code is blocking what you’re trying to do.

It is well known that CSS (which stands for Cascading Style Sheets) works from the top down. This means that, generally speaking, code that is further down in the document takes precedence over other code higher up. A simple example of this is having two declarations targeting the same element:

 

p {
  color: blue;
}
p {
  color: green;
}

 

The color of paragraph elements in this example will always be green, since it appears after the declaration assigning the color of blue to paragraphs.

The problem is that selectors beyond just element selectors have varying levels of specificity, and combining selectors will increase their specificity, overriding other rules.

Elements and pseudo-elements

Elements and pseudo-elements have the lowest level of specificity. Since they target all instances of a given element, using element selectors should only be used when you really want those styles to be applied to all instances of paragraphs, divs, headers, etc. For example, the following code will apply a 1px solid black border to all paragraph elements in the document.

 

p {
  border: 1px solid black;
}

 

Classes, attributes and pseudo-classes

Classes, attributes and pseudo-classes have a higher level of specificity, and will only apply to elements associated with them. They are reusable, in the sense that you can have classes applied to multiple different elements, whenever you want them to share the same styles. These styles will also override styles that conflict with those at the element level. In the example below, all paragraph elements will be green, except for any with the class of alert, which will be red:

 

p {
  color: green;
}
p.alert {
  color: red;
}

 

IDs

IDs have one of the highest levels of specificity, and will override almost anything. Unlike classes which can be reused as many times as you want, IDs are only supposed to be applied to a single element on the page.

 

p#myParagraph {
  color: black;
}
p.alert {
  color: red;
}
p {
  color: green;
}

 

Even though there are two further declarations for paragraphs underneath the p#myParagraph declaration, the ID of #myParagraph will always be black.

Inline styles

Inline styles have an even higher level of specificity than IDs. While it is generally very frowned upon to apply any styles inline, as it makes it difficult to find and manage the styles applied to elements, there are situations where it can be justified.

<p style="color: red;">My red paragraph</p>

 

The above inline style will always be red, regardless of what styles are applied elsewhere.*

!important

The one caveat to the above, even including inline styles, is the use of !important. Whenever !important is added to a CSS rule, this rule will take precedence over all else, always, no matter what:

 

p {
  color: blue !important;
}

 

!important can be a lifesaver when you cannot figure out what is blocking your CSS, but it can also be easily abused and just make your code more of a mess. As a general rule, use !important only when all else fails.

An extremely handy tool for better understanding and checking specificity is Keegan Street’s Specificity Calculator. Whenever in doubt, it can very useful to check your selectors here.

Using WOW.js and Animate.css for Scroll-Triggered Animations

WOW.js and Animate.css

Animations are a great way to add visual excitement and motion to your websites, and the popular animate.css library has provided an easy way to add CSS-based animations to any website. What if you want to only trigger these animations once the user has scrolled to a specific section of your website, though?

This can of course be accomplished via jQuery, but using the JavaScript library for that function alone adds unnecessary bulk for a function that can otherwise be accomplished by a simple script. WOW.js solves this problem, offering an easy-to-use library for adding animations triggering by scrolling, with no jQuery required, in only 3kB.

This post will provide a guide on using WOW.js and animate.css for your web projects, including various options available for installing it.Click To Tweet

If you are interested in learning about different animations besides scroll effects, head to the last section of this blog post for a list of other CSS and Javascript animation libraries.

About animate.css

Using WOW.js and Animate.css for Scroll-Triggered Animations 2019 update

Using CSS animations is a straightforward and easy method to add eye-catching visual effects to any HTML website. One of the most popular libraries for CSS animations is animate.css. While the library may be small, it is a perfect tool for novice web developers who are looking to add more spunk to their website without the complex use of keyframing. While this blog post will mainly be discussing how to use WOW.js, the animate.css file is extremely versatile and can be used with other files as well.

Some of the many animations that you can add to elements on your site include:

  • Static animations: These types of animations appear right when you load and open up a webpage. In other words, no scrolling (WOW.js) involved!
  • Scroll animations: These types of animations appear when the user scrolls into the element’s view on a webpage. This is the type of animation we will be focusing on with WOW.js. This animation can also be created with jQuery.
  • Click animations: With a combination of jQuery and Javascript programming, you can create animations on your website that run when the user clicks on a certain element.
  • “Special” animations: These quirkier animations can be used on elements when you really want to capture the user’s attention instantly with an eye-catching animation.

About WOW.js

WOW.js is a Javascript file that, when added to your HTML document, can create compelling and dynamic effects on a site. This scroll effect is one of the most popular options for web designers, as it used to be licensed as open-source code under MIT. When you are on a website that implements WOW.js, the animated elements will magically appear as you scroll down the site. For an example of this effect, visit the official website for WOW.js. It is a great design tool to utilize with animate.css.

Compared to other animation options with Javascript, WOW.js is extremely popular for its simple, bulk-free code. Note that you can use other CSS animation libraries to activate WOW.js; WOW.js just treats animate.css as its default library. This includes libraries such as CSShake or DynCSS. WOW.js is free to use for open source project, although requires purchase of a license for any commercial projects.

Adding animate.css and WOW.js to your project

In order to start animating your website, the first step is to add animate.css and WOW.js to your HTML document. There are a few ways you can go about adding the files into your HTML project. You can download the distribution for animate.css and WOW.js from each of their respective official sites, or simply link to the files available from CDN. CDN hosts a vast collection of libraries for Javascript and CSS.

A major benefit of using animate.css for your website is that the CSS code is held in just one file, which simplifies your project immensely. Once you add the CSS file to your project, all you must do is link it to your HTML in the head of the document. Alternatively, you can simply link the CDN file to your HTML document. Depending on whether you directly add the animate.css file or simply link to the CDN file, only the href will slightly vary:

<head>

<link rel=“stylesheet” type=“text/css” href=“animate.css”>

<link rel=“stylesheet” type=“text/css” href=“https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.css”>

</head>

Install animate.css and WOW.js

Click the links below to view the animate.css and WOW.js files on CDN:

(Note: “Minified” code refers to the removal of white space and shorter characters in order to preserve functionality but create more compact file sizes. This will make the code more difficult to read and edit for those who want to customize or make changes to the code.)

Using npm to install animate.css and WOW.js

Alternatively, you can use a package manager such as npm (Javascript package manager) to install both animate.css and WOW.js just by merely typing a few keywords into the command line. From the root of your project directory, run the following command from the command line:

npm install wowjs

One benefit of installing WOW.js via npm is that it automatically also installs animate.css as a dependency. This way, you do not need to concern yourself over following the instructions of downloading animate.css with one of the options discussed above. Similar to adding the file directly or using CDN, animate.css will be linked in theof your document (the href path will differ depending on the file location):

<link rel=“stylesheet” href=“node_modules/animate.css/animate.css”>

For the script, you can add WOW.js to your website by linking it at the bottom of your HTML document, just below the closing tag. This must be followed by a <script> tag to activate WOW.js, as demonstrated below:

<script src=“node_modules/wowjs/dist/wow.min.js”></script>

<script>

new WOW().init();

</script>

Adding animations to elements

Once both files are added to the project, it’s time to select the HTML elements that you’d like to animate upon scrolling. Any element with a class of .wow will remain hidden until the user reaches it on the page. You can apply this class to headings, text, images, or even a larger portion of your website enclosed in a <div> tag.

Add a class of .wow to any HTML element you’d like to animate with WOW.js, such as an h1 element:

<h1 class=“wow”>Welcome to my site!</h1>

Animate.css has 75 different animation styles to choose from, all of which can be demoed on the official site (see above). Once you’ve selected an animation you’d like to use, add its name as a CSS class on the element to animate, along with the class “wow.” Here are a few examples of animate.css and WOW.js in action on your HTML document:

<h1 class=“wow fadeInRight”>Welcome to my site!</h1>

The h1 element will now fade in right once the user has scrolled to it on the page.

<div class=“wow pulse”>Click here</div>

The content enclosed in the <div> tag will now create a pulsing effect on the site once the user has scrolled to it on the page.

Alterations to WOW.js Animations

There are slight adjustments that can be made to the CSS animations through some in-line editing on your HTML document. You can add these four properties after class = “wow” and even combine them within any HTML tag. Essentially, these simply properties are a great and effortless way for users to add versatility to the scroll animations. Below are descriptions of the four properties you can alter when animating an HTML element with WOW.js:

  • data-wow-delay=“_s”: Typically, the element automatically appears when the user scrolls to its location. With this property, you can delay the animation for _ seconds.
  • data-wow-duration=“_s”: You can make the animation last _ seconds, which is useful for speeding up or slowing down the element’s appearance.
  • data-wow-iteration=“_”: With this property, you can make the animation repeat, or iterate, _ times before it turns static on your page.
  • data-wow-offset=“_”: This property allows the animation to start _ pixels from the browser edge before animating.

Alternative Animation Libraries to animate.css and WOW.js

Bounce.js

Bounce.js is an easy-to-use tool to create stunning CSS3 and Javascript animationsBounce.js is an easy-to-use tool to create stunning CSS3 and Javascript animations for your website in just minutes. Developers can experiment with a list of various animations on the Bounce.js web tool to generate static keyframes and even customize the animations directly in the web browser. When the animation satisfies your standards, you can export the CSS code directly from the site and paste it into your project. Then, you can use the animations that you created in the web browser and directly apply it to elements on your HTML document. The web tool even generates a unique, shortened URL that allows you to access your animation on a new web browser in case you want to make edits to it at any time.

To learn more about creating animations with Javascript and installing the Bounce.js library into your project, you can follow the instructions for installing the Bounce.js library on its Github site.

Anime.js

Anime.js, which utilizes CSS properties, Javascript objects, SVG, and DOM attributes to create impressive animationsAnother popular animation library is Anime.js, which utilizes CSS properties, Javascript objects, SVG, and DOM attributes to create impressive animations. Julian Garnier’s collection features dozens of seamless animations that you can directly add to your own site. You can view the various animations created with Anime.js on the Anime.js Codepen collection. Unlike WOW.js, this animation library is not necessarily used to animate HTML elements on a site. Rather, Anime.js is used to create separate animated “illustrations” for your website altogether to add to its visual appeal. Some of my favorites include Garnier’s line drawing animation and the layered animations demonstration. To add the Anime.js library to your project, you can install via npm.

View the directions and documentation for using Anime.js on the Github site.

Hover.css

Hover.css produces eye-catching effects on your website by simply hovering your mouse over animated elements.Hover.css produces eye-catching effects on your website by simply hovering your mouse over animated elements. You can use this animation library to add more spunk to ordinary, 2D elements such as buttons, logos, or images. On the Hover.css website, you can browse and test the various animations such as background, 2D, shadow, and outline transitions by hovering your mouse over each button. Those who plan on using one or few Hover.css animations can simply download the file and copy/paste the specific animation into their own stylesheets. However, if you plan on using many Hover.css animations, then you can essentially follow the same procedure of installing and linking the Hover.css stylesheet to your HTML document. You will have access to all Hover.css effect to animate any appropriate HTML element on your site.

To view the specific instructions and documentations for installing and using Hover.css, go to the official Github site.

Typed.js

Using WOW.js and Animate.css blog post: Typed.js overviewTo create the iconic typewriter or typing effect, a popular option for web developers is to use Typed.js. Many websites use this animation library to create string-typing effects on pages, including the popular group workspace platform, Slack. Simply install the Hover.css library via npm or link the CDN file to your HTML document. With essentially one <script> tag, you can animate an HTML text tag with the typewriter effect. With enough tweaking, you can create more advanced typing effects on your website for an even more stunning effect. For instance, you can create the effect of the computer pausing as it types or the effect of deleting letters in a word.

The official Github site includes all of the source code and detailed documentation on how you can customize the typing animation to meet your personal preferences.

CSShake

CSS shake is a collection of animations that all “shake” HTML elements As the title implies, this CSS library is a collection of animations that all “shake” HTML elements on your website. This quirky animation is perfect if you want to draw attention to a certain image or section of your website. It also makes the elements of your website more interactive, which is always a plus for front-end development. You can experiment with the variation of shake animations yourself on the CSShake website by hovering over different elements on the page. The source code on CSShake Github also includes detailed documentation that describes how to create your own custom shake animations. You will have to understand and learn to adjust the jQuery properties by reading the documentation.

When you are ready to install CSShake onto your own project, follow the instructions for installation on the Github site.

Introduction to CSS flexbox & Advanced CSS Selectors

CSS Flexbox (or Flexible Box Layout) was a late addition to the CSS3 specification, aiming to address many of the layout issues of a webpage, especially when working with multiple device sizes and responsive web design. While the more recent CSS grid properties are capable of creating complex grid-based layouts, flexbox is often a better choice for laying out small groups of components within a larger layout, generally with far less code than when using grid. This post will give a short introduction to using the flexbox properties for common layout issues.

display: flex

The first step to creating a flexbox is applying a display: flex property to a parent element that will act as a container for all flex items within it.

While most layouts will require the use of additional properties. A simple 2-column layout can be created using this property alone.

For example, we can take a container with 2 div elements stacked on top of each other, and transform it into a 2-column layout with the addition of the display: flex property:

Original Code:

HTML

<div id="container">
    <div id="column1"></div>
    <div id="column2"></div>
</div>

 

CSS:

#container {
    height: 600px;
    width: 800px;
}
#column1 {
    background-color: blue;
    height: 300px;
    width: 400px;
}
#column2 {
    background-color: green;
    width: 400px;
    height: 300px;
}

 

Introduction to CSS flexbox

CSS with flexbox:

#container {
    height: 600px;
    width: 800px;
    display: flex;
}
#column1 {
    background-color: blue;
    height: 300px;
    width: 400px;
}
#column2 {
    background-color: green;
    width: 400px;
    height: 300px;
}

 

Introduction to CSS flexbox

flex-direction

We can add additional control over the flow of elements in our flex container via the flex-direction property. By default all elements within a flex container will flow in a row from left to right, although we can also set this property to have values of column, row-reverse or column-reverse.

Adjusting spacing and alignment with justify-content

Oftentimes there will be more space in a container than what the elements within it take up, so it is likely that you’ll want to justify the spacing of the elements in a certain way. By default, all elements within a flex container will align to the very beginning of the container (referred to as flex-start) but there are a variety of other options. Note that the actual position will vary depending on the the setting of flex-direction: if the direction is set as row then flex-start will indicate all the way to the left of the container, while a direction of column would indicate the very top of the container for flex-start.

Returning to our original code example, we’ll increase the width of our container a bit to better show the different justify-content settings.

justify-content: center will place all of the elements directly in the center of the column:

<div id="container">
    <div id="column1"></div>
    <div id="column2"></div>
</div>

 

#container {
    height: 600px;
    width: 1000px;
    display: flex;
    justify-content: center;
}
#column1 {
    background-color: blue;
    height: 300px;
    width: 400px;
}
#column2 {
    background-color: green;
    width: 400px;
    height: 300px;
}

 

Introduction to CSS flexbox

justify-content: flex-end is the opposite of justify-content: flex-start, placing the elements at the very end of the container:

CSS flexbox tips

justify-content: space-between will place all elements on each end of the container, leaving whatever space remains at the center of the container, as well as around any additional elements inside (in instances of a container with 3 or more elements):

CSS flexbox hacks

justify-content: space-around is just like spae-between, although there is additional space on the very ends of the container:

CSS flexbox tips & tricks

Advanced CSS3 Selectors

There are numerous other more advanced selectors though, for the purpose of targeting elements with a greater level of specificity. Being familiar with the right selector for the job is one of the most important aspects of learning CSS. This post will highlight some of the most useful advanced selectors for targeting elements.

Child Selectors

Child selectors are used to target elements nested in one another. There are two different kinds of Child selectors, descendant and direct child selectors.

Descendant Selectors

Descendant selectors are used to to target a given element (or group of elements), regardless of where they are nested in their parent element. For example:

.container p

 

would target both instances of the p element in the following HTML:

<div class="container">
    <p>This is a paragraph</p>
    <div>
        <p>This is another paragraph nested further down.</p>
    </div>
</div>

 

Direct Child Selectors

If you only want to target elements that are in the next level down from the parent element, the Direct Child selector is the one to use.

.container > p

 

would only select the first p element in the following HTML:

<div class="container">
    <p>This is a paragraph, targeted by the Direct Child selector</p>
    <div>
        <p>This is another paragraph, not targeted by the Direct Child selector</p>
    </div>
</div>

 

Sibling Selectors

General Sibling Selectors

General Sibling selectors will select any element on the same nested level that appears after the first sibling. For example:

h1 ~ div

 

will target the 2 noted div elements that appear after the h1, but not the one before it, or any that might be nested on further levels:

<div class="container">
    <p>A paragraph</p>
    <div>
        <img src="https://google.com/dog.jpeg" />
    </div>
    <h1>The title</h1>
    <div>This div will be targeted</div>
    <p>Another paragraph</p>
    <div>This div will also be targeted</div>
</div>

 

Adjacent Sibling Selectors

The Adjacent Sibling selector is used to target elements that appear directly after a given element. For example:

h1 + p

 

will only target the p element right after the h1:

<div class="container">
    <p>...</p>
    <h1>...</h1>
    <p>This paragraph will be targeted</p>
    <div>
        <p>...</p>
    </div>
    <p>...</p>
</div>

 

Pseudo-classes

In the previous CSS selectors post, we touched on pseudo-classes via the :hover selector. There are many other pseudo-classes, however, such as :link, :visited, :active and more.

To style an a link that hasn’t been visited yet, use the :link selector:

a:link { color: green; }

 

To stlye an a link that has been visited, use the :visited selector:

a:visited { color: blue; }

 

The :active selector can be used for whenever a user engages with an element, such as clicking on it:

.click-me:active { border-radius: 50%; }

 

:focus is used whenever an element has “focus”, such as a form element when the user has entered it via a mouse or keyboard click:

a:focus { height: 120%; }

Conclusion

Do you find something useful CSS tricks in this post? Please share your comments below.

 

angelo frisina sunlight media

Author Bio

Angelo has been involved in the creative IT world for over 20 years. He built his first website back in 1998 using Dreamweaver, Flash and Photoshop. He expanded his knowledge and expertise by learning a wider range of programming skills, such as HTML/CSS, Flash ActionScript and XML.

Angelo completed formal training with the CIW (Certified Internet Webmasters) program in Sydney Australia, learning the core fundamentals of computer networking and how it relates to the infrastructure of the world wide web.

Apart from running Sunlight Media, Angelo enjoys writing informative content related to web & app development, digital marketing and other tech related topics.

Post a Comment

Comments are moderated. Your email is kept private. Required fields are marked *

© 2020 Sunlight Media LLC