4841 0 March 24, 2015

Do you really need to subtract pixels from percent?

The problem is here from some time on – let’s imagine you have a div, that should be 100% wide, but it also has got some padding, and it fixed width of pixels. Countless developers tried to make the equation 100% – 50px work and failed.

Today we have calc css value, which allows us to perform such tasks, and works pretty well, at least in modern browers.

I see it in use quite often (yes, I do have a nasty habit of checking websites’ source code and css), however I want to talk about underestimated, and often not even noticed, css3 property: box sizing.

Box sizing can have two possible values (except of initial and inherit of course): content-box and border-box. The most important thing about this property is that it makes exactly what we envision when we think about a container that needs to have some percentage width and fixed px padding – it changes the box model, to make the padding count as part of the box width. So, we can simply write:

div { 	width: 100%;
		padding: 50px;
		-webkit-box-sizing: border-box;
     	-moz-box-sizing: border-box;
        box-sizing: border-box;	}

And this will do exactly what is necessary (content-box is a default model in which padding and borders add to the box width). Browser support is not the most awesome that I’ve ever seen, but it works for me, and I think it’s a great step towards simple, semantic and down to earth code, and I definitely prefer to use it instead of intricate calc(100% – 3em) solutions.

Another place where usage of the box-sizing property can’t be overrated is form styling. I remember countless hours I’ve been spending trying to make text input fields and dropdowns the same width and height! I usually like to have some padding on inputs, and I really suffered making complex structures field with divs with negative margins to achieve that. Fortunately it’s not here anymore, forcing

box-sizing: border-box

on all elements we want to have equal does the job. Thank you, box-sizing!

Leave a Reply