Why do you need to add a meta viewport tag inside the <head> element? (with example)
Have you ever wondered why you need to add:
<meta name="viewport" content="width=device-width, initial-scale=1">
inside <head>
tag and why it is useful?
You're in the right place!
Example
First of all, open this web page in a new tab: http://www.pakistan.gov.pk/
Open developer tools and enable device mode in your browser. This mode simulates the behavior of the web app on a mobile device. Notice that the page is zoomed out to fit the fixed-width content on the screen. This is not a good experience because the content will likely be too small for most users, forcing them to zoom and pan.
Set the visual viewport
1- Edit head element:
2- Add viewport:
Then add viewport meta tag and check the page in device mode. Notice the page is no longer zoomed out and the scale of the content matches the scale on a desktop device. If the content behaves unexpectedly in the device emulator, toggle in and out of device mode to reset it.
<meta name="viewport" content="width=device-width, initial-scale=1">
Explanation
A meta viewport tag gives the browser instructions on how to control the page's dimensions and scaling. The width
property controls the size of the viewport. It can be set to a specific number of pixels (for example, width=500) or to the special value device-width
, which is the width of the screen in CSS pixels at a scale of 100%. (There are corresponding height
and device-height
values, which can be useful for pages with elements that change size or position based on the viewport height.)
The initial-scale
property controls the zoom level when the page is first loaded. Setting the initial scale improves the experience, but the content still overflows past the edge of the screen.
So then you need to use CSS flex
or grid
and other properties to make it responsive. But this is the part of another blog story 😜
Thanks, Awesome DEVs!