使用 CSS 媒体查询检测屏幕宽度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7050696/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 01:16:51  来源:igfitidea点击:

Detect screen width with CSS Media Queries

cssmedia-queries

提问by benhowdle89

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.

在某些时候,CSS 样式表必须知道屏幕的宽度,没有 Javascript。

Is this the case?

是这种情况吗?

回答by Madara's Ghost

You can use device-widthwhich will test of the screen's width in px. That however is not entirely recommended. Use max-widthand min-width(for the viewport) instead.

您可以使用device-widthwhich 以 px 为单位测试屏幕的宽度。然而,这并不完全是推荐的。改用max-widthand min-width(用于视口)。



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.

如果您试图获取屏幕宽度并使用它(类似于content: (device-width);某种类型,那是不可能的。坚持使用 JavaScript。

Manual Reference

手册参考

回答by Chris

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.

CSS 并不真正知道浏览器的视口宽度是多少,就像浏览器知道什么 CSS 适用于特定视口一样。

回答by Steve

Well...

好...

@media(width:1024px){
  p#id:after{
    content:"1024px";
  }
}

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.)

如果视口的宽度为 1024 像素,则在指定的 <p> 元素后显示文本“1024px”。您可以(假设)放置数千个这样的 CSS 块来显示视口的宽度,以获取任何合理的宽度值。(请注意,在某些浏览器中无法选择文本。)

The more you know... (please don't actually do this)

你知道的越多......(请不​​要真的这样做)

回答by Puru Thakkar

In html ->

在 html ->

<meta name="viewport" content="width=device-width">

OR

或者

In CSS ->

在 CSS ->

@viewport {
  width: device-width;
  }

Hope it helped.

希望它有所帮助。