Margin only works with float element or display table

Hi everyone.
I’m building a website and I have two divs, one below the other.
The div below has a margin-top: 40px; property, however, it only works if I float that div or if I display it as table. What is the best way to position divs? I don’t like to use floats too much unless I have divs side by side. I also don’t like to use relative positioning since the elements are not truly on the flow.
Any ideas?
Thank you in advance.

it only works if I float that div or if I display it as table
Hi,
You may have ran into collapsing margins, hard to say without seeing your code though.
That’s what it sounds like though as margins do not collapse on floats, inline-blocks, or display:table

To un-collapse child margins you can set a top/bottom padding (or border) on the parent or you can also use overflow:hidden.

You should be able to set a class on any element that needs a different margin or target it exclusively if it is already unique.

Something like this -


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
 "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Test Page</title>

<style type="text/css">
#wrap {
    width:600px;
    margin:0 auto;
    padding:1px 0;/*un-collapse child margins*/
    background:#CCC;
}
.test {
    width:500px;
    min-height:200px;
    margin:19px auto;
    background:lime;
}
.lower {margin-top:40px;}
</style>

</head>
<body>
    <div id="wrap">
        <div class="test">20px top margin here</div>
        <div class="test lower">40px top margin here</div>
    </div>
</body>
</html>

It didn’t work. But I actually solved the situation with a simple height. I had an ul with no height defined.Each li was an image so I thought the height was implicit.

THank you