Jonathan Fogelström Jonathan Fogelström - 1 month ago 14
CSS Question

Incorrect positioning of divs when using height in percentage

I'm not sure if this problem has been posted before, but I don't know how to ask this question effectively.

In my website I've created two large sections one after the other (not referring to the tag), one's height is set to 100% and the other is set to 90%. I've added a div directly underneath the second section. To keep the div stuck I've set "top" to 190% in order to simulate the length of the two sections. Although I've set a minimum height to each section, which makes the div crawl underneath the sections when they've stopped resizing.

How can I avoid this whilst using "position: absolute" for the elements?

html example (using one larger section):

<html>
<body>
<div class="section1"></div>
<div class="box"></div>
</body>
</html>


css example:

.section1 {
display: inline-block; width: 100%; height: 100%; min-height: 500px;
position: absolute;
}
.box {
width: 100%; height: 200px;
position: absolute; top: 100%; margin-top: 50px;
}


Thanks,

Jonathan

Answer

Just don't use position:absolute.

I'm assuming the reason you had it is because you needed height 100% of the viewport, without using JS. You could use the vh unit, but it doesn't have the best support/reliability.

The easiest way is to simply set html and body to height:100%;:

body,
html {
  margin: 0;
  height: 100%;
}
.full {
  height: 100%;
  background: teal;
}
.shorter {
  height: 90%;
  background: #fbfbfb;
}
footer {
  background: #222021;
  color: white;
  text-align: center;
  padding: 10px;
}
<section class="full"></section>
<section class="shorter"></section>
<footer>Made with love by a kitten</footer>

Note that I did add extra CSS for styling purposes.