Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS margin issues when the container does not have a border

Tags:

html

css

More frequently then not I come across this issue. Generally I use padding instead of the margin or some quick solution to fix my problem but I too know this is not the correct fix.

Without going deep into writing my issue, I like create a fiddle for better understanding. So here is my fiddle.

.container-node {
    margin: 10px;
    background-color: #0f0;
}

.content-node {
    margin: 20px;
    background-color: #f00;
    padding: 5px;
    color:#fff;
}

.border {
    border:1px solid #00f;   
}

The issue that I'm trying to point out is if I've two divs, one inside the other and the inside div is given some margin, it takes the margin value differently if the container is bordered and differently if the container does not have a border.

I appreciate any help or documentation on this. Thanks

like image 769
Rupam Datta Avatar asked Sep 16 '25 18:09

Rupam Datta


2 Answers

http://www.w3.org/TR/CSS2/box.html Read carefully 8.3.1 Collapsing margins

Two margins are adjoining if and only if:

  • no line boxes, no clearance, no padding and no border separate them

The best solution of this ptoblem i know is clearfix. Its not giving padding or overflow but similar to it.

Fiddle

.cf:before,
.cf:after {
    content: " ";
    display: table;
}

.cf:after {
    clear: both;
}
.cf {
    *zoom: 1;
}
like image 112
Flops Avatar answered Sep 18 '25 10:09

Flops


As already pointed out it is a "problem" with collapsing margins. A really good read about this issue can be found here:

http://reference.sitepoint.com/css/collapsingmargins

You could just add a padding of 1px and reduce the margin by 1 like so:

.container-node {
    margin: 9px;
    background-color: #0f0;
    padding: 1px;
}

Applied to your problem: http://jsfiddle.net/n65bX/1/

like image 28
puelo Avatar answered Sep 18 '25 09:09

puelo