CSS Calc alternative

H3AP picture H3AP · Apr 16, 2013 · Viewed 74.2k times · Source

I am trying to dynamicly change the width of a div using CSS and no jquery. The following code will work in the following browsers: http://caniuse.com/calc

/* Firefox */
width: -moz-calc(100% - 500px);
/* WebKit */
width: -webkit-calc(100% - 500px);
/* Opera */
width: -o-calc(100% - 500px);
/* Standard */
width: calc(100% - 500px);

I want also support IE 5.5 and higher, i found the following: expression. Is this the correct usage:

/* IE-OLD */
width: expression(100% - 500px);

Can I also support Opera and the Android browser?

Answer

Danield picture Danield · Sep 2, 2013

Almost always box-sizing: border-box can replace a calc rule such as calc(100% - 500px) used for layout.

For example:

If I have the following markup:

<div class="sideBar">sideBar</div>
<div class="content">content</div>

Instead of doing this: (Assuming that the sidebar is 300px wide)

.content {
  width: calc(100% - 300px);
}

Do this:

.sideBar {
     position: absolute; 
     top:0;
     left:0;
     width: 300px;
}
.content {
    padding-left: 300px;
    width: 100%;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
}

* {
  margin: 0;
  padding: 0;
}
html,
body,
div {
  height: 100%;
}
.sideBar {
  position: absolute;
  top: 0;
  left: 0;
  width: 300px;
  background: orange;
}
.content {
  padding-left: 300px;
  width: 100%;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  background: wheat;
}
<div class="sideBar">sideBar</div>
<div class="content">content</div>

PS: I won't work in IE 5.5 (hahahaha) , but it will work in IE8+ , all mobile, and all modern browsers (caniuse)

Width Demo

Height Demo

I just found this post from Paul Irish's blog where he also shows off box-sizing as a possible alternative for simple calc() expressions: (bold is mine)

One of my favorite use-cases that border-box solves well is columns. I might want to divide up my grid with 50% or 20% columns, but want to add padding via px or em. Without CSS’s upcoming calc() this is impossible… unless you use border-box.

NB: The above technique does indeed look the same as would a corresponding calc() statement. There is a difference though. When using a calc() rule the value of the width of the content div will actually be 100% - width of fixed div, however with the above technique, the actual width of the content div is the full 100% width, yet it has the appearance of 'filling up' the remaining width. (which is probably good enough for want most people need here)

That said, if it is important that the content div's width is actually 100% - fixed div width then a different technique - which makes use of block formatting contexts - may be used (see here and here for the gory details):

1) float the fixed width div

2) set overflow:hidden or overflow:auto on the content div

Demo