Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 994
benhowdle89 Avatar asked Dec 22 '22 10:12

benhowdle89


2 Answers

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

like image 194
Madara's Ghost Avatar answered Jan 06 '23 11:01

Madara's Ghost


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.

like image 37
Chris Avatar answered Jan 06 '23 13:01

Chris