使用 CSS 媒体查询检测屏幕宽度
我猜是因为你可以使用媒体查询来做到这一点:
@media (min-width:500px) { … }
在某个时刻,CSS 样式表必须知道屏幕的宽度,没有 Javascript。
是这样吗?
I'm guessing that because you can do this with Media Queries:
@media (min-width:500px) { … }
That at some point or another, the CSS stylesheet must know what width the screen is, sans Javascript.
Is this the case?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用
device-width
将测试屏幕的宽度(以 px 为单位)。然而,并不完全推荐这样做。使用max-width
和min-width
(对于视口)。如果您尝试获取屏幕宽度并使用它(类似于
content: (device-width);
之类的东西,这是不可能的。坚持使用 JavaScript。手册参考
You can use
device-width
which will test of the screen's width in px. That however is not entirely recommended. Usemax-width
andmin-width
(for the viewport) instead.If you are trying to GET the screen width and use it (something like
content: (device-width);
of some sort, that's not possible. Stick with JavaScript.Manual Reference
当客户端浏览器的视口大小发生变化时,浏览器将重新绘制可见区域。此时,浏览器将检查是否存在与新视口相关的媒体查询样式。
CSS并不真正知道浏览器视口的宽度,就像浏览器知道什么CSS适用于特定视口一样。
As the client browser's viewport changes size, the browser will repaint the visible area. At that point in time the browser will be checking if there are media query styles that are relevant for the new viewport.
The CSS doesn't really know what width the browser's viewport is, so much as the browser knows what CSS is applicable for a specific viewport.
好吧...
如果视口的宽度是 1024 像素,则在指定的
之后显示文本“1024px”。元素。您可以(假设)放置数千个这样的 CSS 块来显示视口的宽度,无论其宽度为任何合理的值。 (请注意,在某些浏览器中无法选择文本。)
您知道的越多...(请实际上不要这样做)
Well...
If the width of the viewport is 1024 pixels, this displays the text "1024px" after the designated <p> element. You could (hypothetically) put several thousands of such blocks of CSS to display the width of the viewport, for any reasonable value of its width. (Note that the text isn't selectable in some browsers.)
The more you know... (please don't actually do this)
在html中->
或者
在 CSS 中 ->
希望有帮助。
In html ->
OR
In CSS ->
Hope it helped.