white space appears top/bottom when I use h1 or div with margin-top or margin-bottom

Could you please tell me why space appears when I put inside a div, another div/id/class/heading with margin top or bottom?

Here is the situation

Thank you!

Answers


adding padding: 1px 0; to the mid divs will stop the margins collapsing out of the boxes, from there you can adjust the default margins on your elements to suit and still have whitespace

example link: here

Add this to the start of your CSS file to reset margins and padding.

* {
    margin: 0px;
    padding: 0px;
}

Then remove "margin-top:30px" from .content-with-margin


Try adding a transparent border to your parent div:

.mid
{
    border-width: 1px 0;
    border-color: transparent;
}

One fix is to append/prepend a virtually empty div to the container like this <div style="padding-top: 1px; margin-top: -1px;"></div>

jsFiddle Example


Because h1 for example has default margin which 'overleaps' the containing block. So you should null the margins at h1. I don't think this happens when you use empty div.

Edit: You can of course deal with this case as Hussein says, but I would rather create div wrapper for your contents. It should work afaik and is more generic way, because you won't have to change paddings and margins at every different element that you will want to put there. But Husseins solution is totally valid. You have more choices how to deal with it.


A 0.1px padding will fix the problem without adding a visible space.

Add this to your div:

.mid {
    padding-top: 0.1px;
}

Need Your Help

best practice for nested category in Mongo and Meteor

mongodb meteor database-design mongodb-query nosql

I want to handle nested category in Mongo and Meteor framework for several Ads. For example like this: