If you are a web developer, you must have heard about viewport, and the below line may seem familiar to you.
<meta name=”viewport” content=”width=device-width, initial-scale=1" />
But do you really understand what this line of code actually does?
The formal definition of a viewport is —
“The viewport defines the area of the screen that the browser can render the content to.”
The definition is a bit tricky to understand, so let me give you some examples.
If the width of the browser window is 768px, the width of the viewport is also 768px.
If I expand the browser window to 1024px, the viewport size also changes to 1024px.
Well, that seems quite simple, but not all the displays have the same pixel density. Suppose your device has a resolution of 2048 × 1080 pixels and you make the browser window to full width, it is not necessary that viewport width will be 2048 pixels.
Like my mobile device has a resolution of 1080 x 2340 pixels but my viewport size is 360 x 648 pixels.
So why is that?
Instead of reporting the width in the number of physical hardware pixels, the browser reports the width in the number of dips or device-independent pixels.
DIP is a unit of measurement, that relates pixels to a real distance. The idea being that a device-independent pixel will take up the same amount of space on a display regardless of the pixel density of the display.
If the hardware pixels are twice the pixels reported by browser (device-independent pixels) then the device has a Device Pixel Ratio or DPR of 2.
The example image above has a DPR of 2.
The 700 DIPs get scaled up to 1400 hardware pixels when the page is rendered on the display.
What will happen if you don't define a meta viewport tag in your HTML code that is supposed to be viewed on small screens also?
Unless you tell the browser that your website was designed to work on a small screen, it assumes that they weren't. And renders the page, as if it were on a screen that was 980 DIPs wide.
Now, imagine that content being scaled to fit on a device that's only 360 DIPs wide. It gets scaled to less than half.
By adding the meta viewport tag to the head element of the page we tell the browser that we know what we are doing. By setting the “width=device-width” in meta viewport tag we instruct the page to match the screen width in device-independent pixels. This allows the page to reflow content to match the screen sizes, whether rendered on a small, medium or large screen.
Previously published at https://medium.com/@shababsaifi/do-you-really-understand-the-viewport-2a732c928de1
Create your free account to unlock your custom reading experience.