0

I want to be able to add top-margin to the nav div without getting scrollbars. Do I have to add overflow: hidden; to the body element or add padding-top to the body element instead of margin-top on the nav class div element? Or is there a better way to achieve this? Why does this even happen?

I was able to reproduce it here: https://jsfiddle.net/dup1d62k/1/

I have a simple html strcuture like this inside the body element:

<div class="nav">
  <div class="item">home</div>
  <div class="item">login</div>
  <div class="item">signup</div>
</div>

And the CSS:

* {
    box-sizing: border-box;
}

html, body {
    margin: 0;
    padding: 0;    
    height: 100%;
}

.nav {
    display: table; // To center without giving a fixed width.
    margin: 0 auto;
    margin-top: 30px;
}
.nav:before, .nav:after {
    display: table;
    content: '';
}
.nav:after {
    clear: both;
}
.nav .item {
    float: left;
    padding: 8px;
    background: #f5f5f5;
}
.nav .item:hover {
    background: #e5e5e5;
    cursor: pointer;
}
.nav .item.active {
    background: #e5e5e5;
}

I get this scrollbar that is 30 px offset because of the top-margin on the nav class div element. After all these years I still don't understand CSS.

Alex
  • 5,671
  • 9
  • 41
  • 81
  • "Do I have to add overflow: hidden; to the body element or add padding-top to the body element instead of margin-top on the nav class div element?" Yes, either one. "Or is there a better way to achieve this?" Not really. "Why does this even happen?" See the duplicate link - but you probably already have an idea why it happens based on your question of if you have to add overflow: hidden or padding-top to body. – BoltClock Mar 23 '17 at 06:27
  • Thank you! I will check it out. – Alex Mar 23 '17 at 06:44

0 Answers0