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

问题描述 投票:2回答:1

我是CSS网格的新手,我不确定是否可以在不使用JavaScript的情况下完成以下操作。

我试图隐藏一个侧边栏,当它将小于200px宽。

但是我只想在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>

例如,让我们说.grid400px宽。然后40%400px160px,但是200px160px更多,所以.sidebar应该不显示或有0宽度。

但如果.grid1000px宽,那么40%1000px400px。由于200px小于400px,它应显示宽度为400px

这可能只与CSS网格,CSS网格和其他CSS指令的组合,或没有JavaScript的情况下不可能吗?

html css css3 css-grid
1个回答
1
投票

如果我理解正确,你可以做这样的事情,这就是你所追求的:

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>
© www.soinside.com 2019 - 2024. All rights reserved.