Search code examples
htmlcsscentering

Center Content horizontally and vertically in <main> Part not on Full Page


so I already created a navigation bar in the <header> part and a footer on my website. I also have a <div class="UUDiv"> with a paragraph and a headline in it in my <main> part. Now, I want to center <div class="UUDiv"> horizontally and vertically but only in the main part. With the following code i only centered it in the center of the whole page, so my Div overlaps with my footer...Here is my Code: \

html {
  height: 100%;
}

body {
  margin: 0;
  min-height: 100%;
  display: flex;
  flex-direction: column;
}

.UUDiv {
  text-align: center;
  position: absolute;
  right: 50%;
  bottom: 50%;
  transform: translate(50%, 50%);
}
<header class="RestHeader">
  <nav class="navigation">Navigation...with
    <ul>
      <li> List </li>
    </ul>etc.</nav>
</header>
<main>
  <div class="UUDiv">
    <h1>Headline</h1>
    <p>Text</p>
  </div>
</main>
<footer>
  <div class="footer">Footer...with
    <ul>
      <li> Another List </li>
    </ul> etc.</div>
</footer>

Thanks for your help!


Solution

  • Instead of positioning your div absolute, you could use flexbox for this. Giving your <main> a display: flex and centering it's content like so:

    main {
      display: flex;
      align-items: center;
      justify-content: center;
    }
    .UUDiv {
      text-align: center;
    }
    

    Then it will stay centered inside your <main>.

    The full example:

    html {
      height: 100%;
    }
    
    body {
      margin: 0;
      min-height: 100%;
      display: flex;
      flex-direction: column;
    }
    
    main {
      display:flex;
      align-items:center;
      justify-content:center;
    }
    .UUDiv {
      text-align: center;
    }
    <header class="RestHeader">
      <nav class="navigation">Navigation...with
        <ul>
          <li> List </li>
        </ul>etc.</nav>
    </header>
    <main>
      <div class="UUDiv">
        <h1>Headline</h1>
        <p>Text</p>
      </div>
    </main>
    <footer>
      <div class="footer">Footer...with
        <ul>
          <li> Another List </li>
        </ul> etc.</div>
    </footer>