Search code examples
htmlcsscss-grid

Why the grids with a sticky div is not working?


As I'm learning css I'm facing a problems with the Grid. it doesnt work on media query so it doesn't stack on each other, It doesnt work even using the "grid-template-areas". This is a problem which is constantly present (even without sticky div). previously I did a try and it wasnt working, but writing the same code on online compiler and then copied and pasted in my VSCode the code magically worked.
Could someone explain me why it doesnt work properly. Thank you!

*{
  box-sizing:border-box;
}

@media screen and (max-width:700px) {
  .grid{
    display:grid;
    grid-template-columns: 1fr ;
    grid-template-rows: 1fr 0.5fr;
  }

  .sx{
    background-color:red;
    grid-row: 1/2;
    grid-column: 1/2;
  }

  .dx{
    border:2px solid blue;
    grid-row: 2/3;
    grid-column: 1/2;
  }
}



.grid{
  display:grid;
  grid-template-columns: 1fr 0.4fr;
  grid-template-rows:1fr;
  min-height:200vh;
}

.sx{
  background-color:red;
  grid-row: 1/2;
  grid-column: 1/2;
}

.dx{
  border:2px solid blue;
  grid-row: 1/2;
  grid-column: 2/3;
}
.par{
  width:100%;
  text-align:center;
  padding: 20px;
  background-color: green;
  position: sticky;
  top:0px;
}
.footer{
  height:25em;
  background-color: grey;
  width:100%;
}
<div class="grid">
  <div class="sx"></div>
  <div class="dx">
    <div class="par">
      <p> ciao ciao ciao ciao ciao ciao ciao ciao ciao ciao ciao ciao ciao ciao ciao </p>
    </div>
  </div>
</div>
<div class="footer"></div>


Solution

  • Media queries should be second in priority after the main styles. See how I arranged the rules in the css.

    *{
      box-sizing:border-box;
    }
    
    .grid{
      display:grid;
      grid-template-columns: 1fr 0.4fr;
      grid-template-rows:1fr;
      min-height:200vh;
    }
    
    .sx{
      background-color:red;
      grid-row: 1/2;
      grid-column: 1/2;
    }
    
    .dx{
      border:2px solid blue;
      grid-row: 1/2;
      grid-column: 2/3;
    }
    .par{
      width:100%;
      text-align:center;
      padding: 20px;
      background-color: green;
      position: sticky;
      top:0px;
    }
    .footer{
      height:25em;
      background-color: grey;
      width:100%;
    }
    
    @media screen and (max-width:700px) {
      .grid{
        display:grid;
        grid-template-columns: 1fr ;
        grid-template-rows: 1fr 0.5fr;
      }
    
      .sx{
        background-color:red;
        grid-row: 1/2;
        grid-column: 1/2;
      }
    
      .dx{
        border:2px solid blue;
        grid-row: 2/3;
        grid-column: 1/2;
      }
    }
    <div class="grid">
      <div class="sx"></div>
      <div class="dx">
        <div class="par">
          <p> ciao ciao ciao ciao ciao ciao ciao ciao ciao ciao ciao ciao ciao ciao ciao </p>
        </div>
      </div>
    </div>
    <div class="footer"></div>