Search code examples
htmlcssheaderprogram-entry-point

My Header is Being Included As Part of my Main tag


When I apply margins to my main tag in an attempt to have it appear below the header, it moves the whole page down not just the main section. Why is the main section not appearing below the header?

I have tried using divs as well as the semantic HTML tags.

body {
  font-size: 1.5em;
  line-height: 1.6;
  font-weight: 400;
  font-family: "Roboto", sans-serif;
  color: #222;
}

header {
  text-align: center;
  width: 100%;
}

header h1 {
  float: left;
}

nav {
  margin: 25px 25px;
  float: left;
}

nav ul {
  margin: -17px 0 0 15px;
  list-style-type: none;
}

nav ul li {
  display: inline-block;
  padding: 5px;
}

nav ul li a {
  text-decoration: none;
}

.nav-button {
  float: right;
  margin-top: 10px;
  margin-right: 5px;
}

.nav-button a {
  color: #fff;
  text-decoration: none;
}

main {
  margin-top: 20px;
}

.container {
  position: relative;
  max-width: 820px;
  margin: 0 auto;
  padding: 0 20px;
  box-sizing: border-box;
}

.banner {
  margin-top: 50px;
}
<body>
  <header>
    <h1>Website Title</h1>
    <nav>
      <ul>
        <li class="navbar-item"><a href="#">Nav Item</a></li>
        <li class="navbar-item"><a href="#">Nav Item</a></li>
        <li class="navbar-item"><a href="#">Nav Item</a></li>
      </ul>
    </nav>
    <button class="button-primary nav-button"><a href="#">Button</a></button>
  </header>
  <main>
    <div class="container">
      <div class="banner">
        <h1>Welcome to A Website</h1>
        <p>Simple subheading</p>
      </div>
    </div>
  </main>
</body>

I'm expecting the main section e.g. the banner containing <h1>Welcome to A Website</h1> and <p>Simple subheading</p>

to be displayed below the header section however it is being shown within the center of the h1/nav and the button. Applying a Margin to the banner or container causes the whole page including the header to move down.


Solution

  • What I think is the reason is that the elements inside your header tags are bigger than its container.

    So what you can try are the following alternatives:

    Try 1:

    Give your header a particular Height so that the main div can come below it :

    header
    {
     height: 110px ; /* Approx */
    }
    

    Try 2:

    Add margin-top to the main tag

     main
    {
     margin-top: 7% ; /* Approx */
    }
    

    This may give you the expected result.