Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hiding grid items

Tags:

html

css

css-grid

I am new to css grid. I am not trying to use any frameworks. I have a template where I have 3 columns in desktop browsers, but I want a particular row to only have two columns (one of them does not display) in mobile browser. Is my display: none in my media query the best practice or is there a better way?

.hg_header {
  grid-area: header;
}

.hg_footer {
  grid-area: footer;
}

.hg_main {
  grid-area: main;
}

.hg_left {
  grid-area: altnav;
}

header {
  background-color: yellow;
}

main {
  background-color: white;
}

aside {
  background-color: gray;
}

footer {
  background-color: black;
}

.hg {
  display: grid;
  grid-template-areas: "header header header" "altnav main main" "footer footer footer";
  grid-template-columns: 150px 1fr 150px;
  grid-template-rows: 100 1fr 50px;
  min-height: 100vh;
}

@media screen and (max-width: 600px) {
  .hg {
    grid-template-areas: "header" "main" "footer";
    grid-template-columns: 100%;
    grid-template-rows: 100px 1fr 50px;
  }
  .hg_left {
    display: none;
  }
}
<header class='hg_header'>HEADER</header>
<main class='hg_main'>MAIN</main>
<aside class='hg_left'>ASIDE</aside>
<footer class='hg_footer'>FOOTER</footer>
like image 385
Energetic Pixels Avatar asked Feb 28 '26 01:02

Energetic Pixels


1 Answers

Grid Layout is designed for sizing and positioning grid items. It's not a tool for removing elements from a layout. For that purpose, display: none is a clean and valid solution.

Here's a simplified version of your code:

body {
   display: grid;
   grid-template-areas: "header header header" 
                          "altnav main main" 
                        "footer footer footer";
   grid-template-columns: 150px 1fr 150px;
   grid-template-rows: 100 1fr 50px;
   height: 100vh; 
 }
 
header { grid-area: header; background-color: yellow; }
main   { grid-area: main;   background-color: white;  }
aside  { grid-area: altnav; background-color: gray;   }
footer { grid-area: footer; background-color: black;  }
 
@media screen and (max-width: 600px) {
   body {
     grid-template-areas: "header" "main" "footer";
     grid-template-columns: 100%;
     grid-template-rows: 100px 1fr 50px;
   }
   
   aside { display: none; }
 }

body   { margin: 0; }
<header>HEADER</header>
<main>MAIN</main>
<aside>ASIDE</aside>
<footer>FOOTER</footer>

jsFiddle demo

Related posts:

  • hide elements not specified in grid-template-areas
  • How to hide implicit grid rows?
like image 121
Michael Benjamin Avatar answered Mar 01 '26 17:03

Michael Benjamin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!