June 3, 2024
Media Queries
Media queries allow you to apply CSS rules based on the characteristics of the device displaying the content, such as its width, height, orientation, and resolution. This enables you to create responsive designs that adapt to different screen sizes and devices.
Example:
@media (max-width: 600px) {
body {
background-color: lightblue;
}
}
Responsive Units: Percentages, EMs, REMs, VW, VH
Responsive units allow you to create flexible layouts that adapt to different screen sizes:
div {
width: 50%;
}
div {
font-size: 2em; /* 2 times the font size of the parent element */
}
div {
font-size: 1.5rem; /* 1.5 times the root element's font size */
}
div {
width: 50vw; /* 50% of the viewport width */
}
div {
height: 50vh; /* 50% of the viewport height */
}
Mobile-First Design
Mobile-first design is an approach where you design for mobile devices first and then add styles for larger screens. This ensures that your website is optimized for the smallest screens and gradually enhances the experience for larger screens.
Example:
/* Mobile styles */
body {
font-size: 14px;
}
/* Tablet styles */
@media (min-width: 600px) {
body {
font-size: 16px;
}
}
/* Desktop styles */
@media (min-width: 1024px) {
body {
font-size: 18px;
}
}
Exercise: Making a Responsive Portfolio Page
Let's create a responsive portfolio page using the responsive design techniques we've learned.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Responsive Portfolio</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<header>
<h1>My Portfolio</h1>
</header>
<section class="projects">
<div class="project">Project 1</div>
<div class="project">Project 2</div>
<div class="project">Project 3</div>
<div class="project">Project 4</div>
</section>
</body>
</html>
body {
margin: 0;
font-family: Arial, sans-serif;
padding: 20px;
}
header {
text-align: center;
margin-bottom: 20px;
}
.projects {
display: grid;
grid-template-columns: 1fr;
gap: 10px;
}
.project {
background-color: #333;
color: white;
padding: 20px;
text-align: center;
}
@media (min-width: 600px) {
.projects {
grid-template-columns: 1fr 1fr;
}
}
@media (min-width: 1024px) {
.projects {
grid-template-columns: 1fr 1fr 1fr 1fr;
}
}
Open the HTML file in a browser to see your responsive portfolio page. Experiment with different media queries and responsive units to see how they affect the layout and behavior of your elements.
Coming Up Next
In Chapter 10, we'll explore advanced CSS techniques, including CSS variables, pseudo-classes, pseudo-elements, transitions, and animations, to enhance the interactivity and visual appeal of your web pages.
Please Sign In to post a comment.