简体   繁体   English

当列的宽度在 CSS 网格中小于特定大小时,如何隐藏该列?

[英]How can I hide a column when its width will be less than a certain size in CSS grid?

I am new to CSS grid and am not sure whether it is possible to accomplish the following without resorting to using JavaScript.我是 CSS 网格的新手,不确定是否可以在不使用 JavaScript 的情况下完成以下操作。

I am trying to hide a sidebar when it will be less than 200px wide.当侧边栏宽度小于200px时,我试图隐藏它。

But I only want to show a sidebar when 200px is no more than 40% of the available width.但我只想在200px不超过可用宽度的40%时显示侧边栏。

 .grid { display: grid; grid-template-columns: minmax(0, 200px) 1fr 0; /* what goes here ? */ min-height: 100px; } .grid .sidebar { grid-area: 2 / 1 / 2 / 1; background: red; } .grid .main { grid-area: 2 / 2 / 2 / 2; background: blue; }
 <div class="grid"> <div class="sidebar"></div> <div class="main"></div> </div>

For instance, let's say .grid is 400px wide.例如,假设.grid400px宽。 Then 40% of 400px is 160px , but 200px is more than 160px , so .sidebar should either not display or have 0 width.那么400px 40%160px ,但200px大于160px ,所以.sidebar要么不显示,要么宽度为0

But if .grid is 1000px wide, then 40% of 1000px is 400px .但是,如果.grid1000px宽,那么40%1000px400px Since 200px is less than 400px , it should display with width of 400px .由于200px小于400px ,它应该以400px宽度显示。

Is this possible to do with just CSS grid, a combination of CSS grid and other CSS directives, or not possible without JavaScript?这是否可以仅使用 CSS 网格、CSS 网格和其他 CSS 指令的组合,或者没有 JavaScript 就不可能?

You can do something like this, if I understand you correctly and this is what you are after:你可以做这样的事情,如果我理解正确的话,这就是你所追求的:

 body {margin: 0} /* recommended */ .grid { display: grid; grid-template-columns: minmax(auto, 40%) 1fr; /* first column no more than 40%, ever (from 500px up) */ min-height: 100px; } .grid .sidebar { /*grid-area: 2 / 1 / 2 / 1;*/ background: red; } .grid .main { /*grid-area: 2 / 2 / 2 / 2;*/ background: blue; } @media (max-width: 499.99px) { /* screen width (or the .grid) needs to be at least 500px wide, in order to display the .sidebar, because min-width of 200px is exactly 40% of 500px, so display it when 500px and more, but hide it when less */ .grid {grid-template-columns: 1fr} .grid .sidebar {display: none} }
 <div class="grid"> <div class="sidebar"></div> <div class="main"></div> </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM