CSS3 supports 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. CSS 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. lang()
  3. not()
  4. cubic-bezier()
  5. rotate()
  6. scale()
  7. skew()
  8. translate()
  9. nth-child()
  10. nth-of-type()
  11. 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>