媒体查询可以根据 div 元素而不是屏幕调整大小吗? [英] Can media queries resize based on a div element instead of the screen?

查看:30
本文介绍了媒体查询可以根据 div 元素而不是屏幕调整大小吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用媒体查询根据它们所在的 div 元素的大小调整元素的大小.我不能使用屏幕大小,因为 div 只是用作网页中的小部件,其大小可能会有所不同.

I would like to use media queries to resize elements based on the size of a div element they are in. I cannot use the screen size as the div is just used like a widget within the webpage, and its size can vary.

看起来现在正在做这方面的工作:https://github.com/ResponsiveImagesCG/cq-demos

Looks like there is work being done on this now: https://github.com/ResponsiveImagesCG/cq-demos

推荐答案

经过近 十年 的工作 — 由更广泛的 Web 开发人员社区提供提案、概念验证、讨论和其他贡献— CSS 工作组终于为容器查询奠定了一些基础,使其成为写入 CSS Containment 规范的未来版本!有关此类功能如何工作和使用的更多详细信息,请查看 Miriam Suzanne 的 extensive explainer.

After nearly a decade of work — with proposals, proofs-of-concept, discussions and other contributions by the broader web developer community — the CSS Working Group has finally laid some of the groundwork needed for container queries to be written into a future edition of the CSS Containment spec! For more details on how such a feature might work and be used, check out Miriam Suzanne's extensive explainer.

希望不久之后我们就能看到这样一个系统的强大的跨浏览器实现.这是一个艰苦的等待,但我很高兴它不再是我们必须接受的,因为循环依赖或无限循环或你有什么无法克服的 CSS 限制(这些仍然是某些方面的潜在问题)提议的设计,但我相信 CSSWG 会找到方法).

Hopefully it won't be much longer before we see a robust cross-browser implementation of such a system. It's been a grueling wait, but I'm glad that it's no longer something we simply have to accept as an insurmountable limitation of CSS due to cyclic dependencies or infinite loops or what have you (these are still a potential issue in some aspects of the proposed design, but I have faith that the CSSWG will find a way).

媒体查询并非旨在基于页面中的元素工作.它们旨在基于设备或媒体类型(因此将它们称为媒体查询).width, height,其他基于维度的媒体特征都是指任一维度的维度基于屏幕的媒体中的视口或设备屏幕.它们不能用于引用页面上的某个元素.

Media queries aren't designed to work based on elements in a page. They are designed to work based on devices or media types (hence why they are called media queries). width, height, and other dimension-based media features all refer to the dimensions of either the viewport or the device's screen in screen-based media. They cannot be used to refer to a certain element on a page.

如果您需要根据页面上某个 div 元素的大小应用样式,则必须使用 JavaScript 来观察该 div 元素大小的变化code> 元素而不是媒体查询.

If you need to apply styles depending on the size of a certain div element on your page, you'll have to use JavaScript to observe changes in the size of that div element instead of media queries.

或者,自此答案的原始发布以来引入了更现代的布局技术(例如 flexbox 和标准(例如自定义属性),您可能根本不需要媒体或元素查询.Djave 提供一个例子.

Alternatively, with more modern layout techniques introduced since the original publication of this answer such as flexbox and standards such as custom properties, you may not need media or element queries after all. Djave provides an example.

这篇关于媒体查询可以根据 div 元素而不是屏幕调整大小吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆