When I'm designing a web application that I want to be responsive, I frequently use the units vh and vw (which stand for viewport height and viewport width). These are great because they allow you to size things based on a percentage of the viewport height. However, sometimes you want things sized at 100% of the height or width minus a constant, and that's where the calc function comes in handy!
The Problem With Vh and Vw
The css units vh and vw are awesome for sizing things based on a multiple of the height or width of the window. For example, here's a div whose height and width will be exactly half the viewport's height and width, and it will stretch to resize itself even when you resize the window. Now that's nifty! However, it realistically doesn't make sense to have EVERYTHING scale as a percentage of viewport height. For example, suppose you want to create a div that takes up basically the entire page but has a 10px margin on all sides. You could make it's height 98vh or something like that, but the margin is going to be shrinking and expanding along with the div- not what we wanted.
The Calc Philosophy- Why Not Both?
The beautiful thing about the CSS calc function is that it allows you to combine different types of CSS units! So my tough-to-size div described above could be expressed trivially with this css code:
And here's a nicely embedded plunkr demo for you to play with:
It's Regular CSS!
It's pretty funny because at first I was trying to figure out how I would add Sass to my React project so that I could use the calc function in my css code. I was happy to then find out that I didn't need sass at all to use calc! Browsers just support it as straight up css! And at this point it's really supported pretty much everywhere (only not supported by mobile opera, IE 8, blackberry browser, and really old versions of android os.
Building Responsive Sites & Applications
Sometimes you use bitmap images. Sometimes you have headers, footers, or other elements with a fixed height or width. A key part of responsive design is having elements sized and/or positioned proportionally to the height or width of the device size. Now with something like calc(90vh - 20px) we can add in that fixed pixel exception and have pixel perfect precision of our UI elements with any device in a way that is easy to reason about and needs very little code.
The posts on this site are written and maintained by Jim Lynch. About Jim...