How to manage border, padding, margin with dynamic size (percentage)?

My question is how to control the size of an element (let's say div) with a percentage. I have a situation where I made two divs float side by side and both take 50% of the div that contains them. Each of these two divs have 1px borders, 5px margins and some padding. So how am I supposed to manage these static sizes and dynamic sizes of the content (divs). The reason is that I just mentioned, they won't float side by side due to borders, padding and margins that make the size larger (100%).

What are the solutions? In my case, the margin / padding / border sizes are small, so I think I could just set the size a little lower (eg 45%) and hope it fits. But I think this method is sloppy, as if I set the pad size higher I would have to adjust the div size through trial and error until I find the perfect size. Is there a correct way to achieve this?

Many thanks.


source to share

2 answers

The clean work can be done by creating two floating divs with a border of 0 and 0, only 50% wide. Then, inside each, you can put a div that matches its container with static margin and padding.

Alternatively, you can keep everything dynamic, so put something like margin: 1%, you get nice behavior when the window is resized!




/* support Firefox, Safari/WebKit, Opera and IE8+ */

.example {
   -moz-box-sizing:    border-box;
   -webkit-box-sizing: border-box;
    box-sizing:        border-box;


you can use box-size: border-box so that 50% is then applied to the inner + padding + border, but unfortunately no customization to add a margin.

However, you can use a div inside a div and use a padding on the outer div to simulate a margin.

here's a JSFiddle example



All Articles