Kilian Valkhof

Building tools that make developers awesome.

Random CSS Thought: Math in CSS

CSS & HTML, 30 December 2006, 2 minute read

After some debate with Prashant from Mintpages, we came up with a new utopia in CSS design. Now, this is just a random thought, but wouldn’t it be awesome to be able to use (simple) mathematics in your CSS? I’m not talking about “new techniques” or anything, just about closing your eyes and imagining all the things that would make CSS even more fun.

for example, say you want a 100% width design, but with a fixed width margin on both sides.

 
#page { 
	margin:0 10px; 
	width:100% - 20px; 
}  

That would be infinitely easier then the current extra div needed (the wrapper div to define the 100% width, and the actual content containing div defining the margins). It would make us developers be able to make even leaner code.

The wrapper div

Another example would be when you want a content div to be 100% height, but without counting the header. Right now, The “logical” way to do that is using a wrapper div with 100% height, and the header and content div inside it. With simple math in CSS, it would be:


#header {
	height:150px;
 	background:#fff url("pretty-header.png") no-repeat 0 0;
}
#content {
	height:100% - 150px;
	background:#fff url("content-bg.png") repeat-y top center;
} 

With this, you’d be able to get rid of the wrapper div, and give the same visual presentation with less code.

Boxes, borders

Or, simply use math to include the border of an element into it’s own width. Say you want two boxes that have a width of 50%, horizontally next to each other, but you want a 5px border around both of them as well, this would be the code:


#box1 {
	width:50% - 10px;
	border:5px solid #000;
	float:left;
}
#box2 {
	width:50% - 10px;
	border:5px solid #fff;
	float:left;
}  

That would save you some fake-border background images and additional div’s, am I right?

Utopia

I’m not certain how easily implementable this would be. You’d say it would be fairly easy, given that every browser already calculates the placement. But by looking at how CSS currently gets parsed, I imagine it would be something that’s not going to happen soon. Who knows, perhaps in CSS4?

Polypane browser for responsive web development and design Hi, I'm Kilian. I make Polypane, the browser for responsive web development and design. If you're reading this site, that's probably interesting to you. Try it out!