Trying to better understand viewport, width, device-width, etc to get better at responsive design

Trying to better understand viewport, width, device-width, etc to get better at responsive design
0.0 0

#1

I made the following simple pen to try to better understand these concepts…

https://codepen.io/glen_v/pen/KRwZyE

It uses media queries to change the background color of a div based on width, and then uses a little bit of JavaScript to print the screen.width inside the div.

When I look at this on my iPhone 6 in portrait vs landscape, the div color changes as I would expect, but the number being printed to the div does not change, even when I load the page already in landscape or use that Go button I added to recall the function. (Screenshots below).

So from what I can tell, the media query recognizes that the screen width is over 400 when I’m in landscape orientation, but the JavaScript function does not. Or does screen.width not mean what I think it means?

I’m also confused about how width and device-width play into the viewport. Every article I’ve read on the subject says you should almost always use width instead of device-width when doing media queries, but every time I see the viewport meta tag mentioned everybody is always saying to use content="width=device-width, initial-scale=1.

I feel like I must be missing something fundamental here. Why would we set the viewport based on device-width, but then set all of our media queries base on width?

Sorry, I know this is more of an amorphous blob of multiple questions rather than one distinct question. Any guidance is appreciated though.

(It won’t let me use more than one upload or more than two links since I’m a new user, so there’s a link to the portrait screenshot below, followed by the landscape portrait in the body).

Portrait: https://i.imgur.com/HBDql5q.png


#2

think what you actually want to get is clientWidth

document.documentElement.clientWidth its inner width of html element

screen.width is actual width of ur screen, you dont cut off part of it everytime you click this button, right?)
https://www.w3schools.com/jsref/prop_screen_width.asp

helpful link https://www.w3schools.com/jsref/dom_obj_all.asp


#3

Thanks for responding! I made a new fork of the pen and added a second div to display the clientWidth. Sure enough, when I view this new fork on my iPhone 6, switch to landscape and refresh the page, the number in my clientWidth div changes to the new screen size (now 667) while the screen.width div does not, so your suggestion most definitely works.

I still don’t understand why screen.width isn’t changing though. If I look at this new fork on my desktop with Chrome DevTools set for iPhone 6 landscape mode, both the screen.width and clientWidth divs show 667 (screenshot here). But when I view it on my actual iPhone 6, the screen width stays at 375 no matter what.