Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
HTML5 meta name = "viewport" doesn't work as expected
The HTML5 viewport meta tag controls how web pages are displayed on mobile devices. When it doesn't work as expected, it's often due to incorrect syntax or conflicting properties.
Common Issues and Solutions
Here are the most effective viewport configurations to fix common display problems:
Method 1: Standard Responsive Design
For most responsive websites, use this configuration:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Responsive Page</title>
</head>
<body>
<h1>This page adapts to screen width</h1>
<p>Content scales properly on all devices.</p>
</body>
</html>
Method 2: Fixed Width with Scaling Control
For fixed-width designs that need precise control:
<meta name="viewport" content="user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, width=400, height=device-height, target-densitydpi=medium-dpi">
Key Properties Explained
| Property | Purpose | Common Values |
|---|---|---|
width |
Sets viewport width |
device-width or pixel value |
initial-scale |
Initial zoom level |
1.0 (no zoom) |
user-scalable |
Allow user zooming |
yes or no
|
Common Problems
Issue: Page appears too small on mobile devices
Solution: Use width=device-width, initial-scale=1.0
Issue: Fixed-width content (like 100px) doesn't display properly
Solution: With initial-scale=1, content smaller than the screen width may not fill the viewport. Consider using responsive design or adjust the scale value.
Testing Your Viewport
<script>
console.log("Viewport width:", window.innerWidth);
console.log("Screen width:", screen.width);
console.log("Device pixel ratio:", window.devicePixelRatio);
</script>
Conclusion
Use width=device-width, initial-scale=1.0 for responsive designs. For fixed layouts, carefully balance width, scale, and user-scalable properties to achieve the desired mobile experience.
