O'Reilly

CSS calc

By on  

CSS is a complete conundrum; we all appreciate CSS because of its simplicity but always yearn for the language to do just a bit more. CSS has evolved to accommodate placeholders, animations, and even click events. One problem we always thought we'd have with CSS, however, was its static nature; i.e. there's really no logic, per se. The CSS calc routine bucks that trend, providing developers an ounce of programming ability within CSS.

The CSS

The calc routine is especially useful when calculating relative widths. Calculations can be additions, subtractions, multiplications, and divisions. Have a look:

/* basic calc */
.simpleBlock {
	width: calc(100% - 100px);
}

/* calc in calc */
.complexBlock {
	width: calc(100% - 50% / 3);
	padding: 5px calc(3% - 2px);
	margin-left: calc(10% + 10px);
}

Be sure to use whitespace around operators so that they aren't construed as positive and negative notations.

CSS calc is another example of CSS taking over the role of JavaScript in layout, and I think it's a great thing. As we move more toward responsive design, calc allows us to use percentages for overall block widths, with just a touch of pixel help for some of its components. Have you used calc for your apps? Share how you used calc!

Track.js Error Reporting

Recent Features

  • Designing for Simplicity

    Before we get started, it's worth me spending a brief moment introducing myself to you. My name is Mark (or @integralist if Twitter happens to be your communication tool of choice) and I currently work for BBC News in London England as a principal engineer/tech...

  • An Interview with Eric Meyer

    Your early CSS books were instrumental in pushing my love for front end technologies. What was it about CSS that you fell in love with and drove you to write about it? At first blush, it was the simplicity of it as compared to the table-and-spacer...

Incredible Demos

  • Using Opacity to Show Focus with MooTools

    I'm a huge fan of using subtle effects like link nudging (jQuery, MooTools) to enhance the user experience and increase the perceived dynamism of my websites. Trust me -- a lot of little things are what take websites to the next level....

  • MooTools Accordion: Mouseover Style

    Everyone loves the MooTools Accordion plugin but I get a lot of requests from readers asking me how to make each accordion item open when the user hovers over the item instead of making the user click. You have two options: hack the original plugin...

Discussion

  1. Browser compatibility ?

    • Sorry for the duplicate! didn’t see I coulld reply directly.

      Hey Adoumas,

      With a google search I found this compatibility table: http://caniuse.com/calc. Not supported in < IE 9, so it's pretty limited if you're dependent upon using this for relative width layouts. It could be useful elsewhere though.

    • srigi

      For people who doesn’t want to click:
      IE9+, Firefox 4+, Chrome 19+, Safari 6+, iOS 6+, overal support 72%.

  2. jessek

    Pardon my ignorance, but what are the benefits of doing this over using ‘box-sizing:border-box’ for responsive layout? I understand that you can mix percentage padding with a hint of static, but why would you want to?

    • You could set a layout width to 100% (responsive), while always leaving {x} pixels of that width for an absolutely positioned block on the right; that’s just one example.

  3. Calc() is quite awesome! Did you know you can use it in gradients and background-size/position too?

    Today’s HTML & CSS Advent 2012 entry is actually about the calc() function too.
    http://advent2012.digitpaint.nl/17/

  4. Hey Adoumas,

    With a google search I found this compatibility table: http://caniuse.com/calc. Not supported in < IE 9, so it's pretty limited if you're dependent upon using this for relative width layouts. It could be useful elsewhere though.

    Rob

  5. One word: awesome. Guess what I will be using in my next project?

  6. I share the words of some mates: Awesome! But hey! This is awesome for building grids! Take a look http://codepen.io/ed1nh0/pen/puhsf Tks for share!

  7. Sweet! I’ll have to try calc() out on my next web app

  8. RR

    Not supported for IE <= 9…

  9. CSS3 calculator … Isn’t it?
    I didn’t have a clue about it before though

  10. Salman Abbas

    **** you Android! I expected better from Google.

  11. unykron

    is there a way I can use calc to find the height of a div’s parent, then divide that by 2 and then apply that to the child div’s position so it is vertically centered within its parent when the parents height is flexible depending on the browser windows size? Or is this strictly java script?

    Side note, it seems ridiculous that there is still no way to effectively vertically center an item on the page in css without a workaround! I can do top: x; bottom: x; why isn’t there a center: x or something!

    • left: 50%; transform: translateX: -50%;
      

      This works since left is based on the container and the transform is based on the object.

  12. Hello David,
    I am trying to solve a quite complicated issue here with the CSS3 calc functionality you are advising here.
    General description of my issue you can read in this forum (where i also bought a Drupal Responsive Theme btw) :
    http://refaktorthemes.com/support/viewtopic.php?f=14&t=84&p=7606#p7606

    Do you think there’s a way to have that calc taking into account of a number of content items going to be listed (horizontally in my case) ?
    Thanks upfront for your advise!
    Bart

  13. Additionally to previous post, i found this as a possible solution (?)
    http://stackoverflow.com/questions/15831657/creating-css-global-variables/18941918#18941918
    If i understand it correctly, some CSS selectors are generated via php scripting, so it should in my opinion be possible to assign content specific values to those variables too…

  14. I’ve written a simple JS script to [detect calc support](http://aklp.gr/how-to-check-if-your-browser-supports-CSS3-s-calc-with-javascript)

  15. I use Modernizr to detect CSS calc support and a jQuery fallback solution in case is not supported.

    
    div#main {
        width: calc(100% - 100px);
        height: calc(100% - 50px);
    }
    
    if(! Modernizr.csscalc) {            
        $(window).resize(function() {
            var width = $(window).width() - 100;
            var height = $(window).height() - 50;
                         
            $("div#main").width(width);
            $("div#main").height(height);    
        });
                     
        $(window).resize(); 
    }
    
  16. Kostas Loupasakis

    You should check vh, vw and vmin then. Once properly supported by browsers, layout creation will be fun again! For real!

  17. Great article, thought I’d share my little experiment using calc and vw to make emails responsive in Gmail.

    http://emailcodegeek.com/responsive-email-in-gmail/

    It’s pretty pointless as it only works on larger devices. The Gmail mobile site and Gmail apps all strip style blocks and linked CSS. Just a bit of fun.

  18. Used calc on a recent project, I needed to use the modernizr tool.

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!

Recently on David Walsh Blog

  • Convert Video to mp3

    Let's all be honest for a moment:  we've all ... not paid for ... music.  Whether it was via a file sharing app like Kazaa or Napster, or it was downloading and seeding on bittorrent, or maybe even downloading a music video and ripping its audio,...

  • Sort git Branches by Date

    I'll be first person to admit I don't do as much git repository maintenance as I should.  I rarely delete branches which have been merged, so a git branch execution shows me a mile-long list of branches that likely aren't relevant.  The best way to find branches I've recently...

  • Best Tools and Resources for Web Professionals in 2015

    Looking for the right resources to help you satisfy the needs of your clients? On the lookout for the best tools to help you increase your revenue? Searching for the right software to help you improve your business? Well, then you’ve come to the right place....

  • JavaScript Polling

    Polling with JavaScript is one of those ugly but important functions within advanced front-end user experience and testing practices.  Sometimes there isn't the event you can hook into to signify that a given task is complete, so you need to get your hands dirty and simply poll for...

  • OSCON Portland:  Conference Giveaway and Discount!

    O'Reilly puts on the best web industry conferences in the world.  These conferences include Fluent Conference, Velocity Conference, and the upcoming OSCON in Portland, Oregon from July 20-24.  Open Source Convention (OSCON) is a conference that focuses specifically on open source developers and the tools and possibilities...