隐藏网格项目

时间:2018-02-11 19:09:39

标签: html css html5 css3 css-grid

我是css网格的新手。我不是试图使用任何框架。我有一个模板,我在桌面浏览器中有3列,但我希望特定行在移动浏览器中只有两列(其中一列不显示)。我的媒体查询中的display: none是最佳做法还是有更好的方式?



.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>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:2)

网格布局用于确定网格项的大小和位置。它不是从布局中删除元素的工具。为此,display: none是一个干净而有效的解决方案。

以下是您的代码的简化版本:

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

相关帖子: