A CSS Animations Tutorial | animation Property in CSS Definition & Example | List of CSS Animation Properties

A CSS Animations Tutorial

In this tutorial, we will be learning completely about CSS Animations. This CSS Animations Tutorial covers basic details like definitions, animation property, and some other mostly used CSS Animation Properties along with JavaScript events for CSS Animations. Simply press on the links available here and understand the concept easily.

What are CSS Animations?

Basically, Animation allows an element to constantly change from one style to another style. So, you can alter as many CSS Properties as many times according to your requirement. In order to utilize CSS Animation, you should define a few keyframes for the animation at first. Keyframes include what styles the element will have at specific times.

animation Property in CSS

The CSSanimation property can be applied to animate several other CSS properties like colorbackground-colorheight, or width. Each animation requires to be determined with the @keyframes at-rule which is then known with the animation property, like so:

.element {
  animation: pulse 5s infinite;
}

@keyframes pulse {
  0% {
    background-color: #001F3F;
  }
  100% {
    background-color: #FF4136;
  }
}

CSS Animation Properties

The illustrated table offers you to check out the CSS Animation Properties:

Property Description
@keyframes Specifies the animation code
animation A shorthand property for setting all the animation properties
animation-delay Specifies a delay for the start of an animation
animation-direction Specifies whether an animation should be played forwards, backwards, or in alternate cycles
animation-duration Specifies how long time an animation should take to complete one cycle
animation-fill-mode Specifies a style for the element when the animation is not playing (before it starts after it ends, or both)
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

Do Read:

Animation Shorthand Property

Let’s consider the below example which uses six of the CSS animation properties to animation shorthand property:

div {
  animation-name: example;
  animation-duration: 5s;
  animation-timing-function: linear;
  animation-delay: 2s;
  animation-iteration-count: infinite;
  animation-direction: alternate;
}

Now, you can get the same effect by applying the shorthand animation property:

div {
  animation: example 5s linear 2s infinite alternate;
}

JavaScript events for CSS Animations

With the help of JavaScript, you can accept and perform the following events:

  • animationstart
  • animationend
  • animationiteration

Pay attention withanimationstart, as it starts on page load then you can always execute your code of javascript after the processing of the CSS. Hence the animation is previously commenced and you can’t stop the event.

const container = document.querySelector('.container')
container.addEventListener(
  'animationstart',
  (e) => {
    //do something
  },
  false
)
container.addEventListener(
  'animationend',
  (e) => {
    //do something
  },
  false
)
container.addEventListener(
  'animationiteration',
  (e) => {
    //do something
  },
  false
)

Which Properties You Can Animate using CSS Animations?

The following list of properties can be animated with the help of CSS Animations. Take a look at the provided list:

  • background
  • background-color
  • background-position
  • background-size
  • border
  • border-color
  • border-width
  • border-bottom
  • border-bottom-color
  • border-bottom-left-radius
  • border-bottom-right-radius
  • border-bottom-width
  • border-left
  • border-left-color
  • border-left-width
  • border-radius
  • border-right
  • border-right-color
  • border-right-width
  • border-spacing
  • border-top
  • border-top-color
  • border-top-left-radius
  • border-top-right-radius
  • border-top-width
  • bottom
  • box-shadow
  • caret-color
  • clip
  • color
  • column-count
  • column-gap
  • column-rule
  • column-rule-color
  • column-rule-width
  • column-width
  • columns
  • content
  • filter
  • flex
  • flex-basis
  • flex-grow
  • flex-shrink
  • font
  • font-size
  • font-size-adjust
  • font-stretch
  • font-weight
  • grid-area
  • grid-auto-columns
  • grid-auto-flow
  • grid-auto-rows
  • grid-column-end
  • grid-column-gap
  • grid-column-start
  • grid-column
  • grid-gap
  • grid-row-end
  • grid-row-gap
  • grid-row-start
  • grid-row
  • grid-template-areas
  • grid-template-columns
  • grid-template-rows
  • grid-template
  • grid
  • height
  • left
  • letter-spacing
  • line-height
  • margin
  • margin-bottom
  • margin-left
  • margin-right
  • margin-top
  • max-height
  • max-width
  • min-height
  • min-width
  • opacity
  • order
  • outline
  • outline-color
  • outline-offset
  • outline-width
  • padding
  • padding-bottom
  • padding-left
  • padding-right
  • padding-top
  • perspective
  • perspective-origin
  • quotes
  • right
  • tab-size
  • text-decoration
  • text-decoration-color
  • text-indent
  • text-shadow
  • top
  • transform.
  • vertical-align
  • visibility
  • width
  • word-spacing
  • z-index
Categories CSS

Introduction to PostCSS – Installation, Plugins Supported | Why Use PostCSS?

Introduction to PostCSS

In this tutorial of PostCSS, you will learn What Exactly is PostCSS, the Advantages of using PostCSS, what are the Plugins supported by the PostCSS. You will be well versed with details such as How Different is PostCSS from Saas, etc. We have covered the PostCSS Installation using the yarn or npm.

What is PostCSS?

PostCSS is a tool for transforming CSS with JavaScript plugins. It provides features via its extensive plugin ecosystem to help improve your CSS writing experience. You can pick the plugins you need or even write a custom one for yourself.

Do note, however, that there are PostCSS plugins that do not transform plain CSS, but operate on Sass-like syntax. One example is the PostCSS Simple Variables plugin, which allows you to implement variables (just like in Sass) that you can reuse throughout your code, as shown below.

$color-brand: darkgrey;
$font-size: 1em;
body {
 color: $color-brand;
 font-size: $font-size;
}

PostCSS Installation

You can use yarn or npm to install PostCSS.

yarn global add postcss-cli
npm install -g postcss-cli

Once you are done, the postcss command would be available in your command line.

Why use PostCSS?

Let’s take a look at a few use cases for PostCSS via the power of its plugins.

Autoprefixing

As previously mentioned, the Autoprefixer plugin will add vendor prefixes to CSS properties using values from Can I Use. This reduces clutter in your code and improves readability. For example, this input:

:fullscreen {
}

Gives this output:

:-webkit-:full-screen {}
:-moz-:full-screen {}
:full-screen {}

Using CSSNext features that browsers understand

With the PostCSS Preset Env plugin, you can write future CSS syntax, and the plugin will convert it to CSS that browsers will understand by working out the necessary polyfill. For example, this input:

@custom-media --med (width <= 50rem);
@media (--med) {
  a { 
    &:hover {
      color: color-mod(black alpha(54%));
    }
  }
}

Gives this output:

@media (max-width: 50rem) {
  a:hover  { 
    color: rgba(0, 0, 0, 0.54);
  }
}

Avoiding errors in your CSS

The stylelint plugin points out errors in your CSS code. It supports the latest CSS syntax. For example, this input:

a { 
  color: #d3;
}

Gives this output:

app.css
2:10 Invalid hex color

Using locally scoped CSS class names

With the CSS Modules plugin, you can write CSS that is locally scoped to components, meaning there won’t be any conflicts between your CSS class names no matter how generic they are. For example, this input:

.name {
  color: grey;
}

Gives this output:

.Logo__name__SVK0g {
  color: gray;
}

Creating stunning grids

The LostGrid plugin uses calc() to create grids based on fractions you define without the need to pass a lot of options. For example, this input:

div {
  lost-column: 1/3 
}

Gives this output:

div {
  width: calc(99.9% * 1/3 -  
  (30px - 30px * 1/3)); 
}
div:nth-child(1n) {
  float: left; 
  margin-right: 30px; 
  clear: none; 
}
div:last-child {
  margin-right: 0; 
}
div:nth-child(3n) {
  margin-right: 0; 
  float: right; 
}
div:nth-child(3n + 1) {
  clear: both; 
}

PostCSS Plugins

PostCSS provides various tools for CSS Processing. Below is the list of popular plugins so that you can have an overview of what’s possible to do with PostCSS.

AutoPrefixer: It Parses your CSS and finds if some rules need a vendor prefix. Autoprefixer do so as per the Can I Use Data so you need not bother whether a feature needs a prefix, or if prefixes you use are unneeded because obsolete. You can write cleaner CSS with the help of the plugin.

cssnext: This is a Babel of CSS and permits you to use modern CSS features and takes care of transpiling them to a CSS digestible to older browsers.

  • Adds prefixes taking help of Autoprefixer.
  • You can use CSS Variables.
  • You can even use nesting same as in Sass.

CSS Modules: PostCSS allows you to use CSS Modules. These Modules aren’t a part of CSS Standard and are a build-step process to have a scoped selectors.

csslint: Linting allows us to write correct CSS and avoid errors. stylint plugin permits you to lint CSS during the build time.

cssnano: cssnano minimizes CSS and makes code optimizations so that the least amount of code is delivered in the production.

How PostCSS is different from Sass and Less?

PostCSS can do the same work as preprocessors like Sass, Less, and Stylus, but PostCSS is modular and, in my experience, faster.

The main difference between PostCSS and CSS preprocessors is that you can pick the features you need. Sass and Less give you lots of features you may or may not use, and which you can’t extend.

There are also PostCSS plugins like PostCSS Sass and PreCSS, which are essentially complete replacements for Sass. This means you could literally write your own preprocessor powered by PostCSS.

Categories CSS

CSS Variables (Custom Properties) – Syntax, Limitations | Reasons to Use Variables in CSS

CSS Variables (Custom Properties)

If you are working with CSS you might have known by now how difficult it is to keep the Code neat in CSS. Using the Same Values in Different Rules can be a difficult task and there are chances of errors. In the case of bigger projects, making changes can mess up something else. You might have a question why use it if it is messy? You can overcome it using the CSS Variables and we have covered all of them in this tutorial.

Reasons to Use Variables in CSS

  • Legible code
  • You can make changes in larger projects too with ease.
  • Overcome or avoid typos
  • Can Make Changes during the Runtime.

What are Custom CSS Properties?

In general, these two features are added

  1. You will have the ability to assign arbitrary values ​​to properties with completely customizable names
  2. Obtain the value of these properties using the var() function.

Here’s a simple example,

root {
    --brand-color: #666;
}

#main {
    color: var(--brand-color);
}

--brand-color is a property we defined with a value #666. And var() is the function by which we can access the previously defined function, resulting in color: #666;.

Syntax

The syntax is much simple and all the properties should begin with the double hyphen (--).

Properties are case sensitive thus,  --brand-color is different from --Brand-color and these both are different from --Brand-Color.

You might be thinking that this syntax is not right. However, the double hyphen present ensures retro compatibility with browsers that don’t support these kinds of functions.

Do Check:

Cascades/Scoping

We can define the properties as local or global. We can access the variables within the scope of the elements in which they are defined. All Child Elements can access the Parents Properties but it’s not the same with parents’ properties.

Custom Properties do follow similar rules as in cascading styles. We can define the same property at various levels of specificity.

tyle>
    :root { --text-color: green; }
    div { --text-color: blue; }
    .error { --text-color: network; }

    * {
        color: var(--text-color);
    }
</style>

<p> I'm green because I got my color from root</p>
<div>I got blue from div selector</div>
<div class="error">
    I'm red because of the .error rule
    <p>Another red here because of inheritance!</p>
</div>

css properties

Note that :root is the topmost element (equivalent to the global scope).  We can assign the same property name to a different value within a child element. Isn’t it interesting?

We can even change values ​​within media queries,

root {
    --gutter: 10px 0;
}
main {
    padding: var(--gutter);
}
@media (min-width: 600px) {
    :root {
        --gutter: 0 0 0 16px;
    }
}

Example:

HTML:

<main>
  <article></article>
  <article></article>
  <article></article>
</main>

CSS:

:root {
  --gutter: 10px 0;
}

main {
  padding: var(--gutter);
  display: flex;
  flex-flow: wrap;
  background-color: green;
}

@media (min-width: 600px) {
  :root {
    --gutter: 16px;
  }
}

article {
  padding: var(--gutter);
  background-color: yellow;
  height: 1rem;
  margin-bottom: 1rem;
  width: 100%;
}

article:last-of-type {
  margin-bottom: 0;
}

Output:

media custom css props

The majority of the CSS preprocessors won’t allow you to define variables within media queries.

It is even possible to define properties from other existing ones,

:root {
    --brand-color: red;
    --header-text-color: var(--brand-color);
}

Note that this doesn’t work with Microsoft Edge 15 due to a known bug.

Although not highly recommended, you can define properties in style tags, <html style = "--color: red;">.

var()

As per the MDN, the var() function has the below syntax,

ar( <custom-property-name>[, <declaration-value>]? )

Where custom-property-name is the name of the property that you are defining. If this is invalid or not present, declaration-value will be used instead.

We can state more than one comma-separated-values, same as font-family. However, be particular with your commas. For example, In order to specify more two values for padding, do it like this,

foo {
    padding: var(--gutter, 10px 0 0 5px);
}

--gutter is the primary value, and “10px 0 0 5px” is used if --gutter is not valid or non-existent.

Limitations

The var() function will not support string interpolation or concatenation.

As opposed to the current preprocessor, we can’t use var() function to define property names.

Circular Dependencies

There are possibilities to have dependencies between properties as in the following example,

root {
    --main-color: #c06;
    --accent-background: linear-gradient(to top, var(--main-color), white);
}

However circular dependencies are not allowed. For example,

:root {
    --one: #c06;
    --two: #ccc;
    --one: calc(var(--two) + 20px);
    --two: calc(var(--one) - 20px);
}

In this case, both –one and –two would be considered invalid. The initial values are not overwritten and remain the same., so they would have their initial value instead of the specified value.

Building Values ​​with calc()

The  calc() function is used to perform calculations and determine CSS values. All modern browsers support this function. We can eve combine this with var() to build values on the fly.

header {
    --gutter: 20;
    padding: calc(var(--gutter) * 1px);
}

In this case, --gutter is defined as a single token with the numeric value 20, a numeric. But padding requires a unit as well (e.g., px). Since you can’t concatenate strings, you can instead multiply by “1px” to have a syntactically correct value.

Building with JavaScript

To obtain the value of a custom property in JavaScript, we use the getPropertyValue() method of the CSSStyleDeclaration object.

tyle>
    :root {--brand-color: cyan; }
    p { color: var(--brand-color); }
</style>

<p>This text is cyan</p>

<script>
    const styles = getComputedStyle(document.documentElement);
    const colorValue = styles.getPropertyValue('--brand-color');
    // colorValue = 'cyan';
</script>

In addition, to define a given value, we use the setProperty() method also of the CSSStyleDeclaration object.

Categories CSS

CSS System Fonts | Web Fonts in CSS | Definition, Syntax & Example Programs on CSS @font-face Property

CSS System Fonts

In this tutorial, we will learn What is CSS System Fonts. Also, you may know web fonts in CSS with Syntax. Moreover, this tutorial makes you familiar with the concept of system fonts in CSS by the available direct links.

System Fonts in CSS

CSS System fonts are worth viewing if you need to develop your website speed to give a better user experience. Since 2008 developers have been ready for using the @font-faceCSS property to do custom fonts on websites. Later more browsers like Safari and Firefox supported the @font-face property and it earns more traction in the developer community. After that, we have seen Typekit pop up in 2009 and later Google Fonts commenced offering a range of serif, sans-serif, and other typefaces for free of charge.

Now the @font-face is fully supported over browsers, and you can embed various fonts on your website. However, you can either host the fonts yourself or embed them from external sources such as Google Fonts.

CSS Web Fonts

Web fonts in CSS are applied to support the use of fonts in CSS, which are not placed on the local system. Once picking the not installed font, simply add the font file on the webserver and it will be spontaneously downloaded when required.

Syntax:

@font-face {
    font details
}

Read More:

Everything appears with a (performance) cost

Although it’s fabulous we’ve seen enough choice and flexibility with fonts, embedding fonts on web pages does occur because of the website speed. Notably, on mobile devices utilizing 3G or 4G connections, it signifies that your website is fast and utilizes the most limited amount of data possible.

While applying custom fonts the problem is the font needs to load before the content is performed so the user is waiting on those resources to load before they are ready to do their task. While system fonts are installed on the device it’s more responsive to access those fonts so it’s a great user experience.

Who uses system fonts?

We can see that plenty of well-known websites using systems fonts are as follows:

  • Medium
  • Bootstrap
  • GitHub
  • Booking.com

Usually, a lot of big websites are driving more towards system fonts at recent times.

Example code for the CSS system font stack

body {
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI",
  "Roboto", "Oxygen", "Ubuntu", "Helvetica Neue", Arial, sans-serif;
}

The above code will perform like this, the browser will go through each of these fonts from left to right, it’ll understand if the device has any of these fonts installed and once it gets one it’ll display that font. In case it can’t obtain any of those font families then it’ll simply display a sans-serif font.

Emojis

In case you need to allow emojis then you have to ask for the system fonts that are used too in CSS with the help of the following code snippet:

body {
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto",
  "Oxygen", "Ubuntu", "Helvetica Neue", Arial, sans-serif, "Apple Color Emoji",
  "Segoe UI Emoji", "Segoe UI Symbol";
}
Categories CSS

The CSS Margin Property – Right, Left, Top, Bottom, Shorthand | CCS Margin Values

The CSS Margin Property

CSS Margin Property is used to define space around elements. It is entirely transparent and doesn’t have any background color. Margin Property Values are not inherited by the Child Elements. There are several properties to set an element margin such as margin-left, margin-right, margin-top, margin-bottom, etc. We can change all properties at once using the shorthand margin property. This tutorial explains all the CSS Margin Properties and the Margin Values in detail.

CSS Margin Properties

Property Description
margin It is used to set all properties in one declaration.
margin-left Used for specifying the left margin of an element.
margin-right Used for indicating the right margin of an element.
margin-top Specifies the top margin of an element.
margin-bottom Sets the bottom margin of an element.

CSS Margin Values

Value Description
auto It allows the browser to calculate a margin.
length It indicates a margin pt, px, cm, etc. Default value of length is 0px.
% Used for defining a margin in percent of the width of containing element.
inherit Inherits the margin from the parent element.

Margin Property

The margin property defines the outermost portion of the box model, creating space around an element, outside of any defined borders.

Margins are set using lengths, percentages, or the keyword auto and can have negative values. Here’s an example:

.box {
  margin: 0 3em 0 3em;
}

Do Read:

CSS Margin Example

<!DOCTYPE html> 
<html> 
<head> 
<style> 
p { 
background-color: pink; 
} 
p.ex { 
margin-top: 50px; 
margin-bottom: 50px; 
margin-right: 100px; 
margin-left: 100px; 
} 
</style> 
</head> 
<body> 
<p>This paragraph is not displayed with specified margin. </p> 
<p class="ex">This paragraph is displayed with specified margin.</p> 
</body> 
</html>

Margin Shorthand Property

Margin is a shorthand to denote multiple margins at a time, depending on the number of values entered. It behaves differently. It accepts up to four values, shown here:

.box {
    margin: <margin-top> || <margin-right> || <margin-bottom> || <margin-left>
}

If fewer than four values are set, the missing values are assumed based on the ones that are defined. For example, the following two rule sets would get identical results:

.box {
  margin: 0 1.5em;
}

.box {
  margin: 0 1.5em 0 1.5em;
}

Thus, if only one value is defined, this sets all four margins to the same value. If three values are declared, it is margin: [top] [left-and-right] [bottom];.

Any of the individual margins can be declared using longhand, in which case you would define only one value per property:

.box {
  margin-top: 20px;
  margin-right: 10px;
  margin-bottom: 20px;
  margin-left: 10px;
}

Values Accepted by Margin Property

Margin accepts any kind of length unit and the most common ones are px, rem, em. It even accepts percentage values and a special value named auto.

Using Auto to Center Elements

Each of the margin properties can also accept a value of auto. A value of auto basically tells the browser to define the margin for you. In most cases, a value of auto will be equivalent to a value of 0 (which is the initial value for each margin property) or else whatever space is available on that side of the element. However, auto is handy for horizontal centering:

.container {
  width: 980px;
  margin: 0 auto;
}

In this example, two things are done to center this element horizontally within the available space:

  • The element is given a specified width
  • The left and right margins are set to auto

Without the specified width, the auto values would essentially have no effect, setting the left and right margins to 0 or else to whatever is the available space inside the parent element.

It should also be pointed out that auto is useful only for horizontal centering, and so using auto for top and bottom margins will not center an element vertically, which can be confusing for beginners.

Collapsing Margins

Vertical margins on different elements that touch each other (thus have no content, padding, or borders separating them) will collapse, forming a single margin that is equal to the greater of the adjoining margins. This does not happen on horizontal margins (left and right), only vertical (top and bottom).

Negative Margins

As you might suspect, while a positive margin value pushes other elements away, a negative margin will either pull the element itself in that direction or pull other elements toward it.

Browser Compatability

CSS Margin Property supports the following browsers.

  • Chrome
  • Android
  • IE Phone
  • Firefox Mobile (Gecko)
  • Internet Explorer (IE)
  • Firefox (Gecko)
  • Safari (WebKit)
  • Safari Mobile
  • Opera
  • Opera Mobile
Categories CSS

CSS Pseudo Classes | What are Pseudo Classes in CSS? | Syntax & Example Programs on Pseudo-classes

CSS Pseudo Classes

What are CSS Pseudo-classes?

Pseudo-classes are predefined keywords.

They are used to select an element based on its state or to target a specific child.

They start with a single colon :.

The most common use case is to style the visited and unvisited links. Also, focus or hover over an element.

The popular pseudo-classes are:

Classes Description
:active an element is activated by the user (e.g. clicked). Mostly used on links or buttons
:checked a checkbox, option, or radio input types that are enabled
:default the default in a set of choices (like an option in a select or radio buttons)
:disabled an element disabled
:empty an element with no children
:enabled an element that’s enabled (opposite to :disabled)
:first-child the first child of a group of siblings
:focus the element with focus
:hover an element hovered with the mouse
:last-child the last child of a group of siblings
:link a link that’s not been visited
:not() any element not matching the selector passed. E.g. :not(span)
:nth-child() an element matching the specified position
:nth-last-child() an element matching the specific position, starting from the end
:only-child an element without any siblings
:required a form element with the required attribute set
:root represents the html element. It’s like targeting html, but it’s more specific.
:target the element matching the current URL fragment (for inner navigation in the page)
:valid form elements that validated client-side successfully
:visited a link that’s been visited

Also Check:

The :hover pseudo-class

The below sample code shows how to use the :hover class to alter the color of links when we place a mouse pointer over that link. Feasible values could be any color name in any valid format.

<html>
   <head>
      <style type = "text/css">
         a:hover {color: #FFCC00}
      </style>
   </head>

   <body>
      <a href = "">Bring Mouse Here</a>
   </body>
</html>

CSS – The :lang Pseudo-class

The:langpseudo-class enables you to set special rules for various languages.

In the illustration below, :lang represents the quotation marks for <q> elements with lang=”no”:

<html>
<head>
<style>
q:lang(no) {
  quotes: "~" "~";
}
</style>
</head>
<body>

<p>Some text <q lang="no">A quote in a paragraph</q> Some text.</p>

</body>
</html>

The :visited pseudo-class

We want to make a link color yellow, before and after the visit:

a,
a:visited,
a:active {
  color: yellow;
}

The :nth-child pseudo-class

:nth-child() deserves a special mention. It can be used to target odd or even children with :nth-child(odd) and :nth-child(even).

It is commonly used in lists to color odd lines differently from even lines:

ul:nth-child(odd) {
  color: green;
    background-color: gray;
}

We can also use it to target the first 4 children of an element with :nth-child(-n+4). Or you can style 1 in every 7 elements with :nth-child(7n).

CSS classes and pseudo-classes

The classes in CSS can be connected with pseudo-classes. So, we can address it as-

Syntax

selector.class: pseudo-class {  
  property: value;  
}

Let’s see the following example to understand the working of it:

<!DOCTYPE html>
<html>
<head>
<style>
body{
text-align:center;
}
div.hello:hover {
  color: red;
  font-size:40px;
} 
</style>
</head>
<body>
<h1>CSS Classes and pseudo-classes</h1>
<h2>Move your cursor to the below text</h2>
<div class="hello">Hello World</p>

</body>
</html>

Output:

css classes and pseudo-classes example

CSS Specificity | Definition, Syntax, Examples | Specificity Rules and Hierarchy of CSS Specificity

In this tutorial, beginners and experienced CSS learners can find the complete guide on Specificity in CSS. Just take a look at the below available direct links and have a quick reference on CSS Specificity.

What is Specificity in CSS?

CSS Specificity is the set of rules applied to CSS selectors in order to determine which style is applied to an element. The more specific a CSS style is, the higher the point value it accrues, and the likelier it is to be present on the element’s style.

Example:

<p class="container">Roger</p>

In CSS, we can specify like:

.container {
  color: yellow;
}

also, we can target the paragraph tags like:

p {
  color: red;
}

By understanding how styles are applied, we can ensure the styles we want to display are being rendered.

CSS can quickly become unruly when we don’t stop to think about architecture for our style sheets, and instead throw a ton of CSS selectors around without thinking about specificity.

By making the most of CSS Specificity, we ensure that our code is organized, and our selectors won’t conflict with one another.

Also Read:

Specificity Rules

Inline CSS>Internal CSS>External CSS

  • CSS style implemented by referencing outside stylesheet that has the lowest precedence and is overridden by Internal and inline CSS.
  • Internal CSS is overridden by inline CSS.
  • Inline CSS has the highest priority and overrides all other selectors.

Example:

<html>
  
<head>
    <link rel="stylesheet" type="text/css" href="external.css">
    <style type="text/css">
        h1 {
            background-color: red;
            color: white;
        }
          
        h2 {
            color: blue;
        }
    </style>
</head>
  
<body>
    <h1>
        Internal CSS overrides external CSS
    </h1>
    <h2 style="color: green;">
        Inline CSS overrides internal CSS
    </h2>
</body>
  
</html>

Output:

css specificity rules example

Hierarchy of CSS Specificity

Every element selector has a position in the Hierarchy of specificity in CSS. The following four categories determine the specificity level of a selector:

  • An inline style is connected directly to the element to be styled. Example: <h1 style=”color: #ffffff;”>.
  • IDs – An ID is a unique identifier for the page elements, like #navbar.
  • Classes, attributes and pseudo-classes – This category contains .classes, [attributes] and pseudo-classes like :hover, :focus etc.
  • Elements and pseudo-elements – This category consists of element names and pseudo-elements, for instance: h1, div, :before and :after.

How to Calculate Specificity?

Remember the process of calculating specificity by having a glance at the below point.

Begin at 0, add 1000 for style attribute, add 100 for each ID, add 10 for each attribute, class, or pseudo-class, add 1 for each element name or pseudo-element.

Examine these three code fragments:

A: h1
B: #content h1
C: <div id="content"><h1 style="color: #ffffff">Heading</h1></div>

Then, the result will produce like this:

The specificity of A is 1 (one element)
The specificity of B is 101 (one ID reference and one element)
The specificity of C is 1000 (inline styling)

As 1 < 101 < 1000, the third rule (C) has a greater level of specificity, and hence it will be implemented.

How Does it Work?

By following the three buckets of CSS specificity, you can learn at a high level of knowledge on how it falls under:

1. Type Selectors & Pseudo-Element

type pseudo

For Example:

p {
} /* 0 0 0 1 */
span {
} /* 0 0 0 1 */
p span {
} /* 0 0 0 2 */
p > span {
} /* 0 0 0 2 */
div p > span {
} /* 0 0 0 3 */

2. Class Selectors, attribute selectors, and pseudo-class selectors

class pseudo class attribute

Example:

.name {
} /* 0 0 1 0 */
.users .name {
} /* 0 0 2 0 */
[href$='.pdf'] {
} /* 0 0 1 0 */
:hover {
} /* 0 0 1 0 */

3. ID selectors

id selector

Example:

#name {
} /* 0 1 0 0 */
.user #name {
} /* 0 1 1 0 */
#name span {
} /* 0 1 0 1 */

Also, there is in-line styling which doesn’t use any CSS rather specify the style in-line with the HTML.

Example:

<p style="color: red">Test</p> /* 1 0 0 0 */

!important Rule

There is another property !important that doesn’t follow any specificity rather it is applied overriding all the CSS properties and specificities.

p {
  font-size: 20px !important;
}

Tips on CSS Specificity

  • The universal selector (*) has no specificity value (0,0,0,0)
  • Pseudo-elements (e.g. :first-line) get 0,0,0,1 unlike their psuedo-class brethren which get 0,0,1,0
  • There’s a highly debatable topic related to using !importantas it overrides all the CSS values. It is also a good practice not to use any id selectors but class selectors.
  • The pseudo-class : not() adds no specificity by itself, only what’s inside its parentheses.

How to Setup Tailwind with PurgeCSS and PostCSS? | Tailwind Installation and Usage

How to Setup Tailwind with PurgeCSS and PostCSS

In this tutorial, we will learn how to use Tailwind with any kind of project. Know how to set up Tailwind with PurgeCSS and PostCSS, how to create a Tailwind File, what do PurgeCSS and PostCSS mean. This tutorial makes you familiar with the concept of How to Remove Unused CSS using the PurgeCSS.

Tailwind Installation

We have to install tailwind via npm or yarn:

npm init -y (if its a barebone project, -y stands for yes)
npm install tailwindcss

Create the Configuration File

We have to create a configuration for a tailwind to use:

npx tailwind init

This will create a file named tailwind.config.js in the root location of our project folder.

PostCSS Config Tailwind

Tailwind needs PostCSS (PostCSS is a software development tool that uses JavaScript-based plugins to automate routine CSS operations) and autoprefixer (Autoprefixer will use the data based on current browser popularity and property support to apply prefixes for you) to work. So we need to apply that in the postcss.config.js file:

module.exports = {
  plugins: [
    require('tailwindcss'),
    require('autoprefixer')
  ]
}

Note: If the postcss.config.js doesn’t exist, we have to create one.

We need to install PostCSS and autoprefixer from npm too:

npm install autoprefixer
npm install -g postcss-cli (-g stands for global)

How to Create the Tailwind CSS File?

Now, we will create a CSS file (style.css) and add these lines at the top:

@tailwind base;
@tailwind components;
@tailwind utilities;

Create the build command

We need to specify a build command that will help us to generate the actual CSS file after compiling with PostCSS and autoprefixer. For that, we need to add the command to the package.json file at scripts like:

"scripts": {
  "build:css": "postcss src/tailwind.css -o static/dist/tailwind.css"
}

Build Tailwind

For building the final CSS file we need to run the command npm run build in the root of the project folder.

The resulting file is in static/dist/tailwind.css

Automatically regenerate the CSS upon file changes

There is a great npm package that will compile our CSS in real-time without running the build command every time after edits. For that we need to install the watch using the command:

npm install watch

Then we need to edit the package.json file at scripts like:

"scripts": {
  "build:css": "postcss src/tailwind.css -o static/dist/tailwind.css",
  "watch": "watch 'npm run build:css' ./layouts"
}

Now for running we simply need to execute the command npm run watch and it’s all good.

Trim the File Size

If we check the final CSS file i.e after building, we can see that it’s huge in size. That large file is never appropriate for web pages. For that, we can actually trim the file to make it smaller than the original.

We need to install two more npm packages:

npm install cssnano
npm install @fullhuman/postcss-purgecss

What is PurgeCSS?

PurgeCSS is a development tool used for removing the unused CSS in a Project. It is the default library to control the Tailwind CSS Bundle Sizes. It removes unused styles and optimizes CSS Build Sizes.

How to Remove Unused Classes from Tailwind with PurgeCSS?

To remove unused CSS we use the following code. Then we add this to our PostCSS configuration file postcss.config.js:

const purgecss = require('@fullhuman/postcss-purgecss')
const cssnano = require('cssnano')

module.exports = {
  plugins: [
    require('tailwindcss'),
    require('autoprefixer'),
    cssnano({
      preset: 'default'
    }),
    purgecss({
      content: ['./layouts/**/*.html', './src/**/*.vue', './src/**/*.jsx'],
      defaultExtractor: content => content.match(/[\w-/:]+(?<!:)/g) || []
    })
  ]
}

In development, avoid too much processing

In development, we can use this just to add prefixes and remove comments. We need to edit the postcss.config.js like:

const purgecss = require('@fullhuman/postcss-purgecss')
const cssnano = require('cssnano')

module.exports = {
  plugins: [
    require('tailwindcss'),
    process.env.NODE_ENV === 'production' ? require('autoprefixer') : null,
    process.env.NODE_ENV === 'production'
      ? cssnano({ preset: 'default' })
      : null,
    purgecss({
      content: ['./layouts/**/*.html', './src/**/*.vue', './src/**/*.jsx'],
      defaultExtractor: content => content.match(/[\w-/:]+(?<!:)/g) || []
    })
  ]
}

 

Write JavaScript loops using map, filter, reduce and find | How to use Map, reduce, and filter in Javascript?

Write JavaScript loops using map, filter, reduce and find

In JavaScript, Map, reduce, and filter is considered array methods. Individually one will iterate over an array and make a transformation or computation. Also, each will return a new array on the basis of the result of the function. In this tutorial, our expert programming team discussed in-depth knowledge on how to write JavaScript Loops using map(), filter(), reduce(), and find():

JavaScript Loops

Loops are generally used, in any programming language, to perform operations on arrays: given an array, you can iterate over its elements and perform a calculation.

map, filter, reduce, find

Those are 3 really powerful array functions:

  • map returns an array with the same length.
  • filter as the name implies, it returns an array with fewer items than the original array.
  • reduce returns a single value (or object).
  • find returns the first items in an array that satisfies a condition.

mapfilter and reduce were introduced in ES5, so you can safely use them as implemented in every browser for years.

find was introduced in ES6/ES2015.

Also Check:

Execute something on every element with a map

A loop would look like this:

const doSomething = (item) => {
  //...
  return item
}
const items = ['a', 'b', 'c']
items.forEach((item) => {
  doSomething(item)
})

With a declarative approach, you tell JavaScript to perform something on every element using:

const items = ['a', 'b', 'c']
const newItemsArray = items.map((item) => doSomething(item))

This generates a new array, without editing the original one (what we call immutability).

Finding a single element in the array

Sometimes you need to look for a specific item in the array and return it.

This is how you would do so with a loop:

const items = [
  { name: 'a', content: { /* ... */ }},
  { name: 'b', content: { /* ... */ }},
  { name: 'c', content: { /* ... */ }}
]
for (const item of items) {
  if (item.name === 'b') {
    return item
  }
}

Here is the non-loop version, using find() (ES6+):

const b = items.find((item) => item.name === 'b')

Here is the same functionality using filter() (ES5+):

const b = items.filter((item) => item.name === 'b').shift()

Note: shift() mutates the array, but the array it mutates is the one returned by filter(), not the original array. If this sounds unacceptable, you can check if the array is not empty and get the first item using b[0].

filter() and reduce() will iterate over all the array items, while find() will be faster.

Iterate over an array to count the property of each item

Use reduce() to get a single value out of an array. For example sum the items content.value property:

const items = [
  { name: 'A', content: { value: 5 }},
  { name: 'B', content: { value: 6 }},
  { name: 'C', content: { value: 7 }}
]

using a loop:

let count = 0
for (const item of items) {
  count += item.content.value
}

can be syntax as

const count = items.reduce((result, { content: { value } }) => result + value, 0)

How to print your HTML with style | CSS Printing with Examples

How to print your HTML with style

Here is the complete tutorial on How to print your HTML with style using CSS. By viewing this page, you will get perfect knowledge on CSS printing, @media print rule, and many more concepts related to it. Just click on the links provided below and start learning regarding print CSS.

CSS Printing

There is a possibility to use CSS for altering the appearance of your web page when it’s printed on paper. You can define one font for the screen version and another for the print version.

The following piece of code defines various font families for screen and print in CSS.

<link rel="stylesheet"
      src="print.css"
      type="text/css"
      media="print" />

CSS @media Print

If you’ve prepared any responsive design, you’ll then know about the@mediarule. As well as diverse screen sizes, @media also let you target “print” media. Here’s an example:

@media print {
  /* These styles will only be used when the page is printed or saved to PDF. */
  h1 { font-size: 16pt; }
}

Using this rule, you can define your standard CSS as normal and then join some custom styles that will only be utilized when printing.

p { margin: 1em 0; }

@media print {
  /* Hide related article links when printing. */
  .related-articles { display: none; }
}

If you want to “zero out” all your standard screen styles and begin from scratch, you can wrap your screen styles in another @media rule:

@media screen {
  /* standard styles here. */
}

@media print {
  /* print styles here. */
}

Do Read:

Page break properties

To ensure the content flows evenly over pages, you’ll require control when content gets split among pages. For instance, it looks awkward if a large heading resembles at the bottom of a page – you want it to commence on a new page rather. Likewise, you may want to evade a table spanning multiple pages if possible.

You can make this using page-break-beforepage-break-after, and page-break-inside. Also, You can set the value for these properties to always or avoid.

h1 {
  /* h1 elements always start on the top of a new page. */
  page-break-before: always;
}

section.city-map {
  /* this section always occupies it's own page or pages. */
  page-break-before: always;
  page-break-after: always;
}

table {
  /* tables don't split across pages if possible. */
  page-break-inside: avoid;
}

Repeat table headings

If your document has tables that span many pages, it’ll be difficult to read when printed except the table headers are repeated at the origin of each page. This is moderately easy to accomplish – simply use the thead and tbody elements in your table.

<table>
  <thead>
    <tr>
      <th>City</th>
      <th>Population</th>
  </thead>
  <tbody>
    <tr>
      <td>Sydney</td>
      <td>4.627 million (2018)</td>
    </tr>
  </tbody>
</table>

thead

Adding or removing content

Sometimes you may require to add content that’s only displayed when printing. For instance- you might want to link URLs to be printed. You can accomplish this with the help of:after pseudo-element:

@media print {
  a[href]:after {
    content: " (" attr(href) ")";
  }
}

You may also desire to hide or show specific elements only when printing. By combining @media and display this can be made pretty quickly.

/* hide the watermark on screens. */
.watermark {
  display: none;
}

@media print {
  /* hide the navidation when printing. */
  nav {
    display: hide;
  }
  /* show the watermark when printing */
  .watermark {
    display: initial;
  }
}

Use emulate CSS media for the development.

In order to fasten up your feedback loop while developing, you can arrange your browser to display print styles. To perform this in Chrome on Mac, open developer tools, later use the command-shift-P shortcut for “Run Command” and search for “Emulate CSS print media type”.

emulate

Other browsers will have a related feature in their dev tools.

Unfortunately, to view page breaks you’ll require to print to PDF manually every moment.

Orphans and Widows

The orphans and widows properties manage how the text in an element is split over pages. Sometimes tweaking these values can increase the readability of your printed document.

p {
  /* if there aren't at least three lines before the page
     break, move the element to the start of a new page. */
  orphans: 3;
}

widows-orphans

The below-left side orphans is set to 2, so the second paragraph starts before the page break. By settingorphansto 3, as on the right, the paragraph is taken down to the start of the next page.

The widows property is the inverse of orphans – it defines the minimum number of lines that can be at the origin of a new page.

Advanced tip: the @page rule

With the @page rule, you can tailor-made the page margin for particular pages.

@page:first {
  /* No margin on the first page. */
  margin: 0;
}

@page {
  /* Set a margin on all other pages. */
  margin: 2cm;
}

Unfortunately, browser support for this is currently a little inadequate and you can only use the :first:last:left, :right, and:blank pseudo-selectors to choose pages.