Home > Back-end >  2 div position fixed not working (html , css)
2 div position fixed not working (html , css)

Time:06-22

I wanted to created two divs both with fixed position, however my div class fixed2 which is background-red when I try put to fixed position the top is like same as the fixed1. Is it possible to move the fixed2 after the height stated in fixed1?

output:

output

.fixed1 {
  height: 80vh;
  background: blue;
}

.fixed2 {
  position: relative;
  height: 80vh;
  background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

<div  style="position: fixed; top: 0; width: 100vh; height: 100vh;">
  fixed 1
</div>

<div  style="position: fixed; width: 100vh; height: 100vh;">
  fixed 2
</div>

CodePudding user response:

Answering based on your comments it would be easier to use Flexbox. You could hardcode the height, but if you only want to ahrdcode the height of the first div you can make use of flexbox to let the 2nd div span the remaining height (flex-grow: 1).

Last but not least just add an overflow rule to the elements such as overflow-y: auto which will not increase the height of an element but addign a scrollbar to scroll overflowing content:

body {
  margin: 0; /* resets the default margin */
  height: 100vh; /* letting the body span the entire viewport */
  display: flex; 
  flex-direction: column;
}

.fixed1,
.fixed2 { /* distribute the space equaly to both divs */
  overflow-y: auto; /* to get a scrollbar during overflow */
}

.fixed1 {
  height: 30%;
  background: blue;
}

.fixed2 {
  background: red;
  flex-grow: 1; /* lets the 2nd div fill the rest of the available screen */
}
<div >
  fixed 1
</div>

<div >
  fixed 2
  <p>this<p>
  <p>is<p>
  <p>just<p>
  <p>a<p>
  <p>very<p>
  <p>long<p>
  <p>text<p>
  <p>for<p>
  <p>demo<p>
  <p>purpose<p>  
</div>

CodePudding user response:

I'm not sure if this is what you asked. But if you want to have the second div below the first one, then you need to set the top with the same height that your first div has. Of course this is if you want to use position: fixed, otherwise there are different ways to do it (in this specific case, you don't even need to clarify the position, it will take the whole screen anyway)

.fixed1 {
  background: blue;
}

.fixed2 {
  background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

<div  style="position: fixed; top:0; width: 100vw; height: 50vh;">
  fixed 1
</div>

<div  style="position: fixed; top: 50vh; width: 100vw; height: 50vh;">
  fixed 2
</div>

  • Related