Developer Tips & Tricks - The CSS3 box-sizing Property

October 12, 2011

Once you've built enough Gadgets, sooner or later you are likely to encounter the same dilemmas as I have. One such dilemma goes something like this -

You want to give your content some room between the borders of the Placeholder so that it does not butt right up against the edges. So you apply a margin around the parent div element to give some space between it and the containing Placeholder (which is also a div). No good. What will happen is that the right and bottom edges of your content will be pushed outside of the Placeholder, resulting in it being cut off.

Get started with Rise Vision

To illustrate, here's the Weather Gadget with a 10px margin and a 1px border applied to the parent div. You can see that the right and bottom borders do not show because they extend beyond the edges of the Placeholder:

 

This is obviously not what we want to have happen. All of the content for a Gadget must be shown within the dimensions of the Placeholder. The Placeholder will not expand to fit that content. You could go into the Javascript at this point and compensate for the margins by explicitly setting the width and height, but this is a rather ugly way to achieve what we want.

So, determined to find a pure CSS solution, the next thing you think to try is to use padding instead of margins, but the problem remains - the content is pushing outside of the Placeholder. Here's what that looks like:

 

In desperation, you change the width and height of the div to 95% and apply an auto-width margin to get the content to center:

 

We're definitely getting closer, and this is the best of the 3 alternatives we've seen so far, but you may notice that the content is not vertically aligned. Vertical alignment is an entirely new issue that I will save for another post.

So what's a digital signage Developer to do? I've found that what works best is to use padding together with the CSS3 box-sizing property. The box-sizing property is used to alter the default CSS box model that is used to calculate widths and heights of elements. By setting it to border-box, you can force the browser to render the box with the specified width and height, and add the border and padding inside the box, as opposed to outside of it:

 

And voila! Our weather is perfectly aligned and does not kiss the edges of the Placeholder: