Home » Tutorials » HTML & CSS » Build Intelligent Layout Using CSS Calc() Property

Build Intelligent Layout Using CSS Calc() Property

Build Intelligent Layout Using CSS Calc() Property

  • Stumble it!
  • Share

Introduction of CSS calc()

Dynamically counting the dimension of an element is really hard for web developers. We have no way of doing any kind of dynamic unit calculations using CSS. For example, it’d be nice to be able to reserve 30% of an area plus a fixed amount of space, say 300px. Well thanks to CSS calc() property, we can do that right now using CSS.

The CSS calc() property allows us to calculate a length value using arithmetic expression, which means we can use it to define the sizes of div, the values of padding, the widths of margin, and so forth.

Using CSS calc()

The CSS calc() can be used in anywhere of CSS style-sheet. The 2 main features of CSS calc() are:

  • Mixing percentages and absolute values.
  • Mixing sizing units.

Let’s take a look at the first one, ‘Mixing percentages and absolute values‘. Let’s say, we want to create something like picture shown below:

Using CSS Calc()

Then we could write our CSS as this:

.child {
	background: #feebe8;
	margin: 0 auto;
	position: relative;
	width: -moz-calc(100% - (80px * 2));
	width: -webkit-calc(100% - (80px * 2));
	width: calc(100% - (80px *2));
}

The CSS calc() property will takes care of the proper width calculation based on .child’s parent width and minus a defined 80px padding for each sides.

Besides that the CSS calc() property allows us to: – ‘Mix sizing units‘. Back in the old days, we have no way to combine two different measurements into one to get a resulting size. But now with the CSS calc() we can set the size of child element relative to, say the current font size by mixing ‘em’ and ‘px’ units. Example:

.child {
	width: calc(1em + 5px); 	
}

Conclusion

The CSS calc() is another example of CSS taking over the role of JavaScript. It’s extremely useful when you are working on responsive layout. The calc() property is now available in Google Chrome 19, Firefox 8 or above and IE9 as well.


  • Create Facebook App Style Slide-Out Navigation
  • Design Your Own Responsive Web Template
  • Solving CSS Float’s Problem

  • http://twitter.com/lordfpx lordfpx

    The problem is that mobiel support is too limited… http://caniuse.com/#search=calc

  • DeAndre Johnson

    Cool but useless at the same time

  • Douglas

    The post image has a typo.

Android, iOS Development Tutorials