1

I know this question has been asked before, but I don't understand how to elements with margin:0 have had their margin 'collapse' - they've had their margin 'extended' to me (to a 15px vertical gap between the two elements - <header> & <nav>.

Here is the HTML code I am using:

<div id="container">
    <header>
      <div class="logo">...</div>
    </header>
    <nav>
      ...
    </nav>
</div>

and CSS styles:

#container {
    width: 1178px;
    margin: 0 auto;
    background-color: #FFF;
}
header {
    height: 102px;
    background-color: #000;
    background-image: url(images/header-bg.jpg);
    margin: 0;
}
nav {
    height: 51px;
    background-image: url(images/navigation-bg.jpg);
    background-repeat: repeat-x;
    margin: 0;
}
.logo {
    width: 268px;
    height: 69px;
    padding: 22px 0 0 31px;
    margin: 0;
    float: left;
}

jsfiddle here.

Community
  • 1
  • 1
Steve
  • 2,066
  • 13
  • 60
  • 115
  • 15px gap between them? I couldn't get from your current code. You may have 22px gap as you've applied padding to the logo. – Bhojendra Rauniyar Mar 03 '16 at 07:13
  • Can you make jsfiddle or plnkr? – martin Mar 03 '16 at 07:13
  • Are you trying to understand margin-collapsing rules? Then [this](http://stackoverflow.com/questions/35337043/when-i-try-to-shift-the-image-upwards-using-negative-margin-the-whole-container/35337103#35337103) will help you better. – Bhojendra Rauniyar Mar 03 '16 at 07:17
  • Thanks for your assistance folks. @Martin: [jsfiddle](https://jsfiddle.net/vok0226c/2/) here. – Steve Mar 03 '16 at 07:35
  • The `ul` has a `margin-top` property which pushes the `nav` down. Remove that to remove the gap. – Chris Mar 03 '16 at 07:39

2 Answers2

3

You have to set margin: 0; for the <ul> element.

By default, browsers set margin-top and margin-bottom to 15px.

#menu-primary-menu {
    list-style-type: none;
    margin: 0;
}

You can see in the image bellow that the <ul> element has margin-top: 15px even though you didn't set it yourself.

Btw, if you want to keep that margin-bottom: 15px then set it on the <nav> element not <ul> because it's inside <nav>. https://jsfiddle.net/cq0LwL8f/1/

enter image description here

martin
  • 93,354
  • 25
  • 191
  • 226
1

As the parent elements collapse when the child element is given float:left or float:right. You need to clear the float in parent element, here in your case parent is UL and child is LI.

Refer the following css, this may solve:

Assuming this HTML structure:

<ul class="clear">
    <li class="floated">...</li>
    <li class="floated">...</li>
    <li class="floated">...</li>
</ul>

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

.clear:after {
    clear: both;
}

Also the 15px gap you see is because of the margin-bottom:15px given.

#menu-primary-menu {
    list-style-type: none;
    margin-bottom: 15px;
}

You can adjust the margin (if required) accordingly.

Nukul Ghosh
  • 81
  • 1
  • 3