gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 00:43:04 26 4
gpt4 key购买 nike

我是 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>

例如,假设 .grid 的宽度为 400px。那么400px40%160px,但是200px又大于160px,所以 .sidebar 应该不显示或具有 0 宽度。

但如果 .grid 的宽度为 1000px,则 40% of 1000px400px。由于 200px 小于 400px,因此它应该以 400px 的宽度显示。

如果没有 JavaScript,这是否可能仅使用 CSS 网格、CSS 网格和其他 CSS 指令的组合,还是不可能?

最佳答案

如果我理解正确的话,你可以这样做:

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>

关于html - 当宽度小于 CSS 网格中的特定大小时,如何隐藏列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52281710/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com