3

I have three divs aligned to the center and the HTML and body area extend beyond the window to accomadate the last div which also adds a scroll bar.

My code

html,
body {
  margin: 0;
  border: 0;
  padding: 0;
  width: 100%;
  height: 100%;
  position: relative;
}

p {
  margin: 0;
  padding: 0;
  border: 0;
}

.top {
  position: absolute;
  margin: 0;
  padding: 0;
  left: 50%;
  top: 0%;
  transform: translate(-50%, 0%);
}

.center {
  position: absolute;
  margin: 0;
  padding: 0;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}

.bottom {
  position: absolute;
  margin: 0;
  padding: 0;
  left: 50%;
  top: 100%;
  transform: translate(-50%, -0%);
}
<html>

<head>
  <title>Position</title>
</head>

<body>
  <div class="container">

    <div class="top">
      <p>I am top div</p>
    </div>

    <div class="center">
      <p>I am center div</p>
    </div>

    <div class="bottom">
      <p>I am bottom div</p>
    </div>

  </div>


</body>

</html>

1 Answers1

2

It's the absolute positioning that's doing this at the bottom of the page, you are placing the footer absolutely with top:100%, which seems to cause overflow by extending the element beyond the boundaries of the body.

I noticed that top:95% on .bottom "fixes" this.

But an even simpler solution would be to just to use flexbox, as this scenario is what it is for, and it's way less work:

body,
html {
  margin: 0;
  padding: 0;
}

.container {
  height: 100vh;
}

.container {
  display: flex;
  flex-direction: column; /*specifies main axis to be vertical*/
  justify-content: space-between; /*main axis positioning*/
  align-items: center; /*cross axis (horizontal) positioning*/
}
<html>

<head>
  <title>Position</title>
</head>

<body>
  <div class="container">

    <div class="top">
      <p>I am top div</p>
    </div>

    <div class="center">
      <p>I am center div</p>
    </div>

    <div class="bottom">
      <p>I am bottom</p>
    </div>

  </div>

</body>

</html>
Scott Weaver
  • 7,192
  • 2
  • 31
  • 43
  • thanks you for your answer. I have never used flex. I never knew such a property existed – user10084528 Jul 15 '18 at 17:45
  • no problem - I edited my code snippet, it's even simpler than i was making it (changed from flexing the entire `.center` div to 100% height, and instead just used `justify-content:space-between` on the container). once you go flex box for layouts, you never go back... – Scott Weaver Jul 15 '18 at 18:09