This section explains the key principles behind responsive web design with examples.
Media queries allow you to apply CSS styles based on conditions like screen width, height, device type, or orientation.
@media (max-width: 768px) {
body {
background-color: lightgray;
}
}
Responsive design ensures that web pages work well across different devices and screen sizes. Principles include:
The viewport meta tag is essential for controlling the layout on mobile devices. It helps to make the design responsive.
<meta name="viewport" content="width=device-width, initial-scale=1.0">
Fluid layouts use relative units like percentages to define widths, so the layout adapts to different screen sizes.
.container {
display: flex;
flex-wrap: wrap;
}
.box {
background-color: lightcoral;
padding: 20px;
text-align: center;
flex: 1 1 200px;
}
With the mobile-first approach, you start by designing for smaller screens first and then use media queries to adapt for larger screens.
/* Base styles for mobile-first design */
body {
font-size: 16px;
}
@media (min-width: 768px) {
/* Styles for tablets and above */
body {
font-size: 18px;
}
}
Responsive images are images that scale to fit the container and adjust depending on screen size.
<img src="image.jpg" class="responsive-image">
CSS units are important for creating responsive layouts. They are divided into two categories: relative units and absolute units.
%
: Percentage based on the parent element's dimensions.em
: Relative to the font-size of the parent element.rem
: Relative to the root font size.vw
: Relative to 1% of the viewport's width.vh
: Relative to 1% of the viewport's height..container {
width: 80%;
height: 50vh;
}
Absolute units are fixed measurements and do not scale. Examples include:
px
: Pixels, an absolute unit for screen display..container {
width: 500px;
height: 300px;
}