In HTML, viewports are used to control the dimensions and scaling of a web page's content within the browser window. The viewport meta tag is commonly used to set these properties. Let's go through some examples:

Example 1: Basic Viewport Configuration

html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Viewport Example</title> <!-- Other head elements go here --> </head> <body> <!-- Your content goes here --> </body> </html>

In this example:

  • The width=device-width ensures that the viewport width is set to the device's width.
  • initial-scale=1.0 sets the initial zoom level to 1.

Example 2: Disabling Zooming

html
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">

This example prevents users from zooming in or out by setting maximum-scale to 1.0 and disabling user scaling with user-scalable=no.

Example 3: Responsive Design with Media Queries

html
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" media="screen and (max-width: 600px)" href="styles/small-screen.css"> <link rel="stylesheet" media="screen and (min-width: 601px)" href="styles/large-screen.css">

Here, different stylesheets are applied based on the screen width using media queries. The viewport settings ensure proper rendering on various devices.

Example 4: Setting a Fixed Width

html
<meta name="viewport" content="width=600">

This example sets a fixed viewport width of 600 pixels. This is not recommended for responsive design but may be useful in certain situations.

Example 5: Handling Viewport Orientation

html
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, orientation=landscape">

This example sets the initial viewport scale and prevents scaling, specifically for landscape orientation. You can also use portrait for portrait orientation.

Example 6: Controlling Viewport Height

html
<meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0">

This example sets the viewport height to the device's height. It ensures that the content is scaled properly based on both width and height.

Example 7: Using the "viewport-fit" Property

html
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">

The viewport-fit=cover property ensures that the entire viewport is covered by the web page, which can be useful in devices with notches or unusual screen shapes.

Remember to adapt these examples to the specific needs of your web project. Viewport settings are crucial for creating a responsive and user-friendly design across different devices and screen sizes.