Plus minus pixels from percentage in css via the awesome calc function

Live Demo

Download Sample

Few months ago also, if people asked me, can we add or subtract pixels from percentage in css, my ans used to be straight forword “NO”. But when CSS 3 was launched with the awesome calc function, it changed my answer to “YES”.

Yes, with this calc function, we can easily add or subtract pixels and percentages in css. Here is a simple piece of code to make you understand.

#div1
{
background-color: #00FF00;
height:40px;
width: calc(50% + 30px);
}

Here the width of the div will be 50% of the width of it’s parent div + 30px extra. You also can use this function to make some complex calculations. For an example, in the following piece of code the margins and width of the div is varying according to the the expressions inside the calc function.

#div2
{
    background-color: #FFFF00;
    height:40px;
    width: calc(2*50%/2 + 2*3*5px);
    margin:calc(2*3*2px);
}

To make this code supportable to all the major browsers you can add the -webkit, -moz, -o prefixes before the calc function.

Live Demo

Download Sample

About This Author

Hello! I am Paul Shan, a JavaScript Expert, Full Stack and DevOps Engineer cum Consultant based out of Bengaluru, India.