We apply responsive design to ensure that a website is readable and visually appealing across all devices, regardless of screen size.
Responsive design refers to the ability of a website to resize and reorganize its content based on:
We also need to think about loading smaller images for mobile devices and user experiences on mobile.
A popular approach for responsive design is a mobile-first approach, in which we plan our design for mobile devices first and then adapt them for a larger screen.
The viewport meta tag is placed inside our <head>
section and tells the browser what width the viewport should be.
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
</head>
Name attribute: viewport
Content of this meta tag:
The width=device-width: specifies that the width of the viewport the device’s width (which will vary depending on the device).
The initial-scale=1.0: sets the initial zoom level when the browser first loads the page.
CSS uses media queries to tell the browser how to style an element at particular screen size.
For example, an image can be styled differently at 500px in width on a mobile device and 1400px in width on a desktop.
Example 1: If the browser window is 1400px or smaller, the font size of H2 will be 40px, and li will be 20px.
@media only screen and (max-width: 1400px) {
h2 {
font-size: 40px;
}
nav li {
font-size: 20px;
}
}
Example 2: If the browser window is 800px or larger, the background color will be light blue:
@media only screen and (min-width: 800px) {
body {
background-color: lightblue;
}
}
Note
min-width
and max-width
.min-height
and max-height
.background-size: cover:
em represents the size of the current font.
For example, if the font is 16 pixels (which is normally the default text size in a browser), then 2 ems equals 32 pixels.
h2 {
font-size: 2em;
}
rem checks the root element.
html {
font-size: 20px;
}
h2 {
font-size: 1.5rem;
}
In the example above, h2 has 30px.
Instead of defining a fixed width using units like px, or cm, percentages can be used to set height, width, padding, and margin.
@media only screen and (max-width: 560px) {
nav li {
font-size: 16px;
display: block;
width: 100%;
margin: 12px 0;
}
}
We can use the min-resolution and max-resolution media features to target by resolution. The resolution value is dots per inch (dpi) or dots per centimeter (dpc)
@media only screen and (min-resolution: 300dpi) {
/* CSS for high resolution screens */
}