Checkout my Getting Started with React video course on Skillshare. It is 100% free.

How to use Counters in CSS

We know that in HTML there we have the ol - ordered lists. By default what they do is to add a counter in front of any element that is on the list.

For example, the below is an ordered list made with ol and li tags:

  1. Cats
  2. Lions
  3. Tigers
  4. Jaguars

Those numbers are added by using CSS Counters. And we can add this behavior to any element we want, not just ordered lists.

Take for example the following HTML code:

<section>
    <h4>The Cats</h4>
    It is the only domesticated species in the family.
</section>
<section>
    <h4>The Lions</h4>
    It is a muscular, deep-chested cat with a short, rounded head.
</section>
<section>
    <h4>The Jaguars</h4>
    This spotted cat closely resembles the leopard, but is usually larger and sturdier.
</section>

If we want to add numbers to all h4 of a section first we will need to set the name and the value to zero for a new counter:

body { counter-reset: sectionsCounter; }

Next for each section we see, we will want to increment the counter:

section {counter-increment: sectionsCounter;}

And finally, use the counter’s value as content for the :before of a h4:

h4: before { content: counter(sectionsCounter) ". "; }

And voila. Now we’ll have section headings like 1. The Cats and 2. The Lions and so on.

See the full example here.

How to use the currentColor value in CSS

In CSS we have a special color value named currentColor that maybe be unknown to most people.

What currentColor does is to take the value for the color property and use it for any other property there has a color parameter.

For example the following:

.red-box {
    color: red;
    border: 2px solid red;
    box-shadow: 5px 10px red;
}

Is the same as having:

.red-box {
    color: red;
    border: 2px solid currentColor;
    box-shadow: 5px 10px currentColor;
}

It provides us with increased flexibility for our CSS. We just have to change the color in one place. Think of it as a CSS variable for colors only.

And it works even with inherited values too. For example:

body {
    color: blue;
}
p {
    border: 1px solid currentColor;
    // will create paragraphs with a blue border
}

Hoever, keep in mind that the rules of cascading apply also here. If we have an inherited value and we set a new color for the child, that new value will have priority.

And it works even with inherited values too. For example:

body {
    color: blue;
}
p {
    border: 1px solid currentColor;
    color: red;
    // will create paragraphs with a RED border
}

What is box-sizing in CSS

The default way for CSS to calculate the total needed space for an element is to sum up the follwing:
totalwidth = 2*margin + 2*border-width + 2*padding + width.

The above example assumes that all of the left - right margins, paddings, and border-width are equal.

If you have a .container with the width: 100px you will not be able to put 2 .column next to each other if you have a width: 50px and a border: 1px solid red. That is because one column will have 50px + 2*1px = 52px and your container only has 100px. While I was learning CSS this was quite an "Aha!" moment for me.

.column {
    border: 1px solid red; 
    width: 50px; // will actually take 52px 
}

.container {
    width: 100px; // will not fit 2 columns
}

But you can change this behavior by setting the box-sizing property.

You can set 2 values for box-sizing:

  • content-box ; the default option
  • border-box

If we set box-sizing: border-box this means that the padding and border-width are included in the width. This can provide provides us with better control for how much space one element will take up.

So, for border-box we will have:
totalwidth = 2*margin + (width - 2*border - 2*padding).

Please note that only the border and padding are included. The margin will still add extra space.

If you want to apply it to every element on the page, out of the box, you can just set:

*, *:before, *:after {
  box-sizing: border-box;
}

Using the CSS calc() function

The calc() is a CSS function that lets you calculate values right in your CSS. For example:

.main-content {
  width: calc(100% - 40px);
}

One of the most useful features of this function is that you can mix multiple CSS units. In our example, we used a percentage with pixels. Bun we can also use units like em, pt, rem, etc.

In 90% of the cases, I find myself using calc with the substractions sign, but you can use it along with:

  • additions by using +
  • subtractions by using -
  • multiplication by using *
  • division using by /

The operator must be wrapped in white spaces. Some operators don't work well if you don't have a white a before and after it.

// use this code 
.logo {
  height: calc(4rem - 30px);
}
// instead of this one
.logo {
  height: calc(4rem-30px);
}

It is supported in all major browsers https://caniuse.com/#feat=calc.

Using calc() with CSS variables and SASS

It works out of the box with the new CSS variables:

--text-input-width: 500px;
max-width: calc(var(--text-input-width) / 2);

Using calc() in SASS or SCSS

For SASS variables you will have to interpolate the value in the calc() function:

$body_padding}: 20px;
 height: calc(100% - #{$body_padding})

CSS Variables explained with 5 examples

The plan for this article is to show you how native CSS variables work, and how you can use them to make your life a bit easier. As your web apps grow bigger, the CSS becomes big, redundant and many times messy. Used within a good context, the CSS variables, give you the mechanism to reuse and easily change repeatedly occurring CSS properties.

Before “the pure” CSS supporting variables, we had pre-processors like Less and Sass. But they required compiling before use, thus (sometimes), adding an extra layer of complexity.

How to define and use CSS Variables (also known as custom properties)

Let me start with something you may already be familiar with: using vars in JavaScript.

To declare a simple JavaScript var you will write something like this:

let myColor = "green";

To declare a CSS variable you will have to add a double dash before the name of that var.

body {
    --english-green-color: #1B4D3E;
}

Now, in order to use the value of the CSS variable, we can use the var(...) function.

.my-green-component{
    background-color: var(--english-green-color);
}

The easiest way to manage your CSS vars is by declaring them into the :root pseudo-class. Given the fact that the CSS variables follow the rules like any other CSS definition, having them in the :root will ensure that all selectors will gain access to these variables.

:root{
    --english-green-color: #1B4D3E;
}

Browser support for CSS variables ?

Browser support for CSS variables isn’t bad at all. If you take a look at Can I Use CSS Variables then you will see that all major browsers are supporting CSS vars out of the box. Both on mobile or desktop.

Just be careful to provide a fallback if many of your users are (still) using IE.

Let’s build stuff!

Now, let's see these CSS variables in action:

Example 1 - managing colors

By far one of the best candidates for using CSS variables are the colors of your design. Instead of copy-and-pasting the same colors over and over again, we can just place them in variables.

If somebody is asking us to update a specific shade of green or make all of the buttons red instead of blue then just change the value of that CSS variable, and that's it. You won’t have to search and replace all of the occurrences of that color.

Example 2 - removing duplicate code

Often you need to build a few different variants of components. Same base styles, just slightly different. Let's use a case with some buttons that are different in color.

The typical solution will be to create a base class, say .btn and add the variant classes.

.btn {
  border: 2px solid black;
  // more props here
}

.btn:hover {
  background: black;
  // more props here
}

.btn.red {
  border-color: red
}
.btn.red:hover {
  background: red
}

And now use them like this:

<button class="btn">Hello</button>
<button class="btn red">Hello</button>

However, this will add some code duplication. On the .red variant we have to set both the border-color and the background to red.

This can be easily fixed with a CSS variable.

.btn {
    border: 2px solid var(--color, black);
}
.btn:hover {
    background: var(--color, black);
}
.btn.red {
    --color: red
}

Example 3 - making some properties human readable

CSS vars are great to use if we want to create a shortcut to a more complex property value, so that we don't have to remember it.

CSS properties, like box-shadow, transform and font or other CSS rules with multiple parameters are perfect examples.

We can place the property in a variable so that we can reuse it via a more human readable format.

Example 4 - cascading the variables

The standard cascade rules also apply to the CSS Variables.

So, if a custom property is declared multiple times, the lowermost definition in the css file overwrites the ones above it.

The following example demonstrates how easy it is to dynamically manipulate properties on user action, while still keeping the code clear and concise.

Example 5 - Theme switcher with CSS Variables

A great thing about CSS variables is their reactive nature. As soon as we update them, whatever property has the value of the CSS variable gets updated as well. So, with just a few lines of Javascript and the smart use of CSS Variables, we can make a theme switcher mechanism.

Bonus tips for CSS Variables

Like almost all the things in CSS, the variables are also pretty straightforward and easy to use. Here are a few more tips that are not included in the examples, but are still very useful in certain situations:

  1. mind your capitalization; CSS variables are case sensitive

    :root {
     --color: blue;
     --COLOR: red;
    }
    /*--color and --COLOR are two different variables*/
  2. when you use the var() function you can send a second parameter. This value will be used if the custom property it's not found:

        width: var(--custom-width, 33%);
  3. you can use CSS variables directly into HTML

    <!--HTML-->
    <html style="--size: 600px">
    body {
      max-width: var(--size)
    }
  4. You can use a CSS variable within other CSS var:

    --base-red-color: #f00;
    --background-gradient: linear-gradient(to top, var(--base-red-color), #222);
  5. CSS variables can be made conditional with media queries. For example, the following code changes the value of the padding, based on the screen size:

    :root {
        --padding: 15px 
    }
    
    @media screen and (min-width: 750px) {
        --padding: 30px
    }
  6. Don't be afraid to use CSS variables with the calc() function.

    --text-input-width: 5000px;
    max-width: calc(var(--text-input-width) / 2);

CSS variables aren't a silver bullet. They will not fix every problem you have in the CSS realm. However, you can quickly tell they make your code more readable and maintainable.

Also, they greatly improve the ease of change across large documents. Just set all your constants in a separate file, and you won’t have to jump through thousands of lines of code when you just want to make a change to a variable.

So, what are you waiting for? Give CSS variables a try and let me know what you think.