Shamss Zaidan
Shamss Zaidan

Reputation: 625

Making grid responsive

Any idea of how to make this grid responsive?

This is my CSS:

body {
  margin: 40px;
}

.wrapper {
    display: grid;
    grid-gap: 10px;
    grid-template-columns: 100px 100px 100px;
    background-color: #fff;
    color: #444;
    }

.box {
    background-color: #444;
    color: #fff;
    border-radius: 5px;
    padding: 20px;
    font-size: 150%;
}

.a {
    grid-column: 1 / 3;
    grid-row: 1;
}
.b {
    grid-column: 3 ;
    grid-row: 1 / 3;
}
.c {
    grid-column: 1 ;
    grid-row: 2 ;
}
.d {
    grid-column: 2;
    grid-row: 2;
}

HTML

<div class="wrapper">
  <div class="box a">A</div>
  <div class="box b">B</div>
  <div class="box c">C</div>
  <div class="box d">D</div>
</div>

I tried this code:

@media only screen and (max-width:500px) {
   .box  {
      width: 100%;  
      margin-right: 0;
      float: none;  
      margin-bottom: 20px !important;
   }

What's the best way to accomplish this?

Upvotes: 3

Views: 1536

Answers (2)

Arvind
Arvind

Reputation: 184

I agree with @Petra that you need to use fr, but use a media query if you want to display them stacked on a mobile device. You could also just change the display to block. Make sure you add these after the initial CSS so that it isn't overridden.

@media screen and (max-width: 512px) {
    .wrapper {
        grid-template-columns: 1fr;
    }
}

Upvotes: 3

Petra
Petra

Reputation: 53

.wrapper {
    display: grid;
    grid-gap: 10px;
    grid-template-columns: 1fr 1fr 1fr;
    background-color: #fff;
    color: #444;
    }

ith CSS Grid Layout, we get a new flexible unit: the Fr unit. Fr is a fractional unit and 1fr is for 1 part of the available space.

Upvotes: 1

Related Questions