开发者

Detect screen width with CSS Media Queries

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?


You can use device-width which will test of the screen's width in px. That however is not entirely recommended. Use max-width and min-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


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.


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

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


In html ->

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

OR

In CSS ->

@viewport {
  width: device-width;
  }

Hope it helped.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜