简体   繁体   中英

vertical gap between elements with margin 0

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.

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/

在此处输入图片说明

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM