Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

html

css

My question is how to manage the size of an element (let's say a div) with percentage. I have a situation where I made two divs float side by side and both takes 50% of the div that contains them. Each of these two div have borders of 1px, margin of 5px and some padding. So how am I supposed to manage these static sizes and the dynamic size of the content (divs). Cause in the case I just mentioned, they will not float side by side because of the borders, padding and margin that make the size over (100%).

What are the solutions? In my case the sizes of margin/padding/borders are small so I guess I could just set the size a bit lower (like 45%) and hope it will fit. But I think this method is sloppy, since if I set the size of the padding higher, I will have to adjust the size of the div with trials and errors until I find the perfect size. Is there a proper way to achieve this?

Thanks a lot.

like image 919
maniak Avatar asked Dec 05 '25 11:12

maniak


2 Answers

A clean work can be made by making the two floating divs with 0 margin and 0 border, just width at 50%. Then inside each you can put a div that fits its container, with static margin and padding.

As alternative, you can keep everything dynamic, so put something like margin:1%, you'll get a nice behavior in window resizing!

like image 145
kappa Avatar answered Dec 07 '25 00:12

kappa


From https://developer.mozilla.org/En/CSS/Box-sizing

/* 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-sizing: border-box so that the 50% then applies to the inner+padding+border, but sadly no setting to add the margin.

You can however use a div inside a div and use padding on the outer div to mimic the margin.

here's an example JSFiddle

like image 35
Dampsquid Avatar answered Dec 07 '25 01:12

Dampsquid



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!