Ron Brouwers Ron Brouwers - 5 months ago 8
CSS Question

CSS Layout - White space when NOT using any padding

First and foremost, I am asking this question for learning purposes and to understand CSS better. Secondly, I am using this normalize version:

https://necolas.github.io/normalize.css/

My question is this. When I set the padding to 0 on my header element, I get a white border at the top of my layout:

Not Working JSFiddle

But, when I set ANY padding amount on my header, it does work:

Working JSFiddle

Anyone can tell me why this is?



html,
body {
height: calc(100% - 100px);
}
body {
font-family: verdana;
}
* {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
.container {
position: relative;
height: 100%;
}
header {
width: 100%;
height: 125px;
padding: 0;
background-color: red;
}
nav {
width: 100%;
height: 50px;
padding-left: 10px;
vertical-align: middle;
line-height: 50px;
background-color: yellow;
}
aside {
float: left;
width: 200px;
height: calc(100% - 25px);
padding: 10px;
background-color: blue;
}
section {
float: right;
padding: 10px;
height: calc(100% - 25px);
width: calc(100% - 200px);
background-color: green;
}
footer {
position: fixed;
left: 0;
bottom: 0;
width: 100%;
height: 50px;
padding-left: 10px;
vertical-align: middle;
line-height: 50px;
background-color: orange;
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/normalize/4.1.1/normalize.min.css" rel="stylesheet"/>
<div class="container">
<header>
<h1>Header</h1>
</header>
<nav>Menu</nav>
<aside>Aside</aside>
<section>Content</section>
<footer>Footer</footer>
</div>




Answer

This is because you have an h1 in your header which margin does not collapse and affects its parent's margin.

To solve this you can add overflow: auto; to your parent element, in this case in your <header> tag.


MORE INFO:

CSS margin-top of affects parent's margin