f w h

Solving Common Design Problems Using CSS Calc()

CSS’s calc() property is one of the lesser known but most useful around. It can solve a number of the more common front end code issues we face, and browser support is surprisingly deep.

First, let’s take a look at how calc() works. calc() can be used in place of any length, frequency, time, number or integer. If, say you wanted to set the width of an element to 90%, but subtract 20 pixels to compensate for another element, you would write it like so: width: calc(90% – 20px);

Note the spaces between the numbers and the operator. The expression will not work without them. It is possible to create more complex calculations and nest parentheses. See the spec for more information.

Compensate for Margins

Say you have 5 elements across, each sized at 20% width, but you need to add a 5px right margin on each for spacing. Add the margin-right:5px; as you normally would. Then, calculate the width like so: width:calc(20% – 5px);

Calculate Width for X Number of Elements

Calculating width for the 5 elements I mentioned above can be done more easily. Simply divide 100% by the number of elements like so: width:calc(100% / 5);. Incorporate the margin compensation, if necessary: width:calc((100% / 5) – 5px);. If rounding errors are a problem, use 99.9% in place of 100%.

Static Width Element + Fluid Width Element + Responsive

Perhaps your right sidebar needs to remain a fixed width, but you need the content area to be fluid. Consider the following HTML:

<aside class="sidebar">
	<!--Sidebar content-->
<section class="main">
	<!--Articles and what-not-->

Let’s say we want the sidebar to be a static 150px wide, but the content area to fit the rest of the area and remain fluid. The relevant CSS would look like this:

	width:calc(100% - 150px);

Centering Elements Vertically and/or Horizontally

There are a plethora of ways to center elements, and this is really just an easier way to do the old left:50%; with a negative half margin trick:

	left:calc(50% - 50px);

These are just a few of the really common front end design problems. The possibilities are endless. What other uses cases do you know of?