Responsive Web Design involves employing HTML and CSS to automatically resize, hide, shrink, or enlarge elements on a website, ensuring it looks appealing on all devices, including desktops, tablets, and phones.
Setting The Viewport
For a responsive website, include the following <meta>
tag in all your web pages.
<meta name="viewport" content="width=device-width, initial-scale=1.0">
This tag sets the viewport of your page, providing the browser with instructions on how to control the page's dimensions and scaling.
Responsive Images
Responsive images are images that scale gracefully to suit any browser size.
Setting the CSS width
property to 100% enables the image to be responsive, scaling both up and down as needed.
<img src="image.jpg" style="width:100%;">
Problem:
In the example above, the image can be scaled up to be larger than its original size, which may make it blur.
Solution:
A solution, in many cases, is to use the max-width
property instead.
By setting the max-width
property to 100%, an image will scale down if necessary but will never scale up to exceed its original size.
<img src="image.jpg" style="max-width:100%;height:auto;">
Responsive Text Size
You can set the text size using the "vw" unit, representing the "viewport width". This approach ensures that the text size adjusts based on the size of the browser window.
<h1 style="font-size:12vw">Hello World</h1>
The viewport refers to the size of the browser window. For example, 1vw (viewport width) is equivalent to 1% of the viewport width. If the viewport is 100cm wide, then 1vw would be 0.5cm.
Media Queries
Media queries allow you to specify distinct styles for various browser sizes.
For instance, the three div elements below will arrange horizontally on large screens and stack vertically on small screens.
<style>
div {
float: left;
width: 33%;
}
@media screen and (max-width: 640px) {
div {
width: 100%;
}
}
</style>
<div>Box 1</div>
<div>Box 2</div>
<div>Box 3</div>
Click here to learn more about CSS media queries.
You will learn more about responsive web design in our HTML Website Development Guide.
Please check below options for the links to our previous or next tutorial.