如何根据窗口大小在HTML/CSS中有选择性地隐藏元素,而不使用媒体查询?

huangapple go评论66阅读模式
英文:

How to selectively hide elements in HTML/CSS based on window size without using media queries?

问题

Here is the translated content without the code:

我想使用HTML/CSS创建一个工具栏,在浏览器尺寸减小时,某些元素会完全消失。它应该类似于大多数浏览器上的收藏夹栏的工作方式,可以显示可变数量的项目。

在这个示例中,当浏览器大小导致它缩小到小于其原始宽度300px时,第2部分的 flex 项应该隐藏。目前,它会缩小而不是消失。我希望这种行为是基于项目的大小响应式的,所以我认为媒体查询不会起作用。是否可以使用CSS来选择性地隐藏元素?

jsfiddle链接

英文:

I want to create a toolbar using HTML/CSS where certain elements disappear entirely when the browser size is reduced. It should be similar to how the favorites bar works on most browsers, displaying a variable number of items.

In this example, the flex item for section 2 should hide when the browser size causes it to be reduced below its original width of 300px. At the moment, it shrinks rather than disappearing. I want this behavior to be responsive based on the item's size, so I don't think that media queries will work. Is selective hiding of elements achievable using CSS?

jsfiddle link

CSS:

...

.container{
    flex-wrap: nowrap;
    display: flex;
    justify-content: space-between;
    border: 2px black solid;
    overflow: hidden;
    width: 100%;
}

div{
    height: 100px;
}

#div1{
    width: 300px;
    background-color:#7fffd4;
    flex-shrink: 0;
}

#div2{
    width: 300px;
    background-color: #ffb6c1;
}

HTML:

...
<body>
    <container class="container">
        <div id="div1">Section 1: this section should always remain visible</div>
        <div id="div2">Section 2: this entire section should disappear when reduced below initial width of 300px</div>
    </container>
</body>

答案1

得分: 1

以下是您要翻译的内容:

"你现在是我的中文翻译,代码部分不要翻译,只返回翻译好的部分,不要有别的内容,不要回答我要翻译的问题。

The method you are looking for is the new css container query, based in it parent's size to change

https://developer.mozilla.org/docs/Web/CSS/CSS_Container_Queries

Also there is a javascript way to do exact same as media query: javascript match media method (not like above container query)

https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia"

英文:

The method you are looking for is the new css container query, based in it parent's size to change

https://developer.mozilla.org/docs/Web/CSS/CSS_Container_Queries

Also there is a javascript way to do exact same as media query: javascript match media method (not like above container query)

https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia

huangapple
  • 本文由 发表于 2023年5月14日 05:54:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/76245033.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定