CSS3 adds support to variables and functions. Even some common functions were already there in previous versions of css, like rgb(), attr() and url(), but with CSS3, we got more functions in css. CSS3 also supports variables using var().

CSS Variables

CSS variables is a new way to store variables in :root selector (i.e html) and use variables value using var function, i.e var(). CSS variables are declared using -- prefix. It is compulsory to use -- prefix otherwise variables are not declared. See example

CSS Variables example


<style>
    :root{
        --bgred:#f66;
        --bggreen:#6f6;
        --bgblue:#66f;
    }
    
    .danger{ background:var(--bgred); }
    .success{ background:var(--bggreen);}
    .info{ background:var(--bgblue);}
    
</style>
               

Functions

In previous versions of css, we use css functions like rgb() color function, attr() attribute function ( content value of ::before or ::after) and url() for file path.

CSS functions example


<style>
    .danger{ background:rgb(255,128,128); }
    .pattern{ background:url(../img/patter.png); }
    .title:before{
        content:attr(title);
    }
</style>
               

New functions in css3

  1. calc()
  2. min()
  3. max()
  4. clamp()
  5. lang()
  6. not()
  7. cubic-bezier()
  8. rotate()
  9. scale()
  10. skew()
  11. translate()
  12. nth-child()
  13. nth-of-type()
  14. nth-last-of-type()

Calc()

CSS Calc function is used to calculate output based on arguments passed. All basic Maths functions can be used in css now using calc function.

Calc Example


<style>
    .container{
        width:calc(100% - 200px);
        margin:auto;
    }    
</style>

Calc divide and multiply


<style>
    .container{
        width:calc(100% / 12);
        height:calc(100px * 2);
        margin:auto;
    }    
</style>

Calc with variables


<style>
   :root{
       --gutter:30px;
       --width:1200px;
       --grids:12;
   }
    .container{
        width:var(--width);
        margin:auto;
    }
    .col-6{
        width:calc(var(--width) / 2);       
    }
            
</style>

min()

CSS min function pick the minimum value from given arguments. min() functions can have one or more comma separated.

width : min(300px,50%)

<style>
    .box{
        width:min(300px, 50%);
    }
</style>

max()

CSS max function pick the maximum value from given arguments. max() functions can have one or more comma separated.

width : max(300px,50%)

<style>
    .box{
        width:max(300px, 50%);
    }
</style>


clamp()

CSS clamp(min, val, max) function can have three values, min, val and max.

width : clamp(300px, 50%, 400px)

<style>
.box{
    width:clamp(300px, 50%, 400px);
}
</style>