CSS MQ Examples - Notes By ShariqSP
Responsive Elements with CSS Media Queries
Below are examples showing how elements adjust automatically for different devices using Media Queries.
Example 1: Responsive Text Size
/* Default styles */
h1 {
font-size: 32px;
}
/* For small screens */
@media (max-width: 600px) {
h1 {
font-size: 24px;
}
}
/* For large screens */
@media (min-width: 1200px) {
h1 {
font-size: 48px;
}
}
Explanation: The heading text size automatically adjusts: smaller on mobile devices (max-width: 600px) and larger on desktops (min-width: 1200px).
Example 2: Two-Column to Single-Column Layout
/* Default styles: two columns */
.container {
display: flex;
}
.container div {
flex: 1;
padding: 10px;
border: 1px solid #ccc;
}
/* For small screens */
@media (max-width: 768px) {
.container {
flex-direction: column;
}
}
Explanation: The layout adjusts from two columns on larger screens to a single-column layout on smaller screens.
Column 1
Column 2
Example 3: Responsive Images
/* Default styles */
img {
width: 100%;
max-width: 800px;
height: auto;
}
/* For small screens */
@media (max-width: 600px) {
img {
max-width: 100%;
}
}
Explanation: The image scales down proportionally on smaller screens to fit the available space while maintaining its aspect ratio.
Example 4: Responsive Navigation Bar
/* Default styles */
nav ul {
display: flex;
justify-content: space-around;
}
nav ul li {
list-style: none;
padding: 10px;
}
/* For small screens */
@media (max-width: 768px) {
nav ul {
flex-direction: column;
align-items: center;
}
}
Explanation: The navigation menu switches from a horizontal layout on larger screens to a vertical stacked layout on smaller devices.