Day 2 - Responsive Design
1. Viewport Units (vw, vh)
vw (viewport width) is relative to the browser window
size.
% (percentage) is relative to the parent element size.
Code:
.vw-box {
width: 50vw;
/* 50% of screen width */
}
.pct-box {
width: 50%;
/* 50% of parent width */
}
Output:
2. Media Queries (@media)
Style changes based on conditions like screen width. This is the core of responsive design.
Code:
.responsive-box {
background-color: #ff5722;
/* Red (Mobile) */
}
@media (min-width: 600px) {
.responsive-box {
background-color: #2196f3;
/* Blue (Tablet) */
}
}
@media (min-width: 900px) {
.responsive-box {
background-color: #4caf50;
/* Green (Desktop) */
}
}
Output:
3. Responsive Layouts
Using Grid or Flexbox with media queries to change column counts.
Code:
.responsive-grid {
grid-template-columns: 1fr;
/* 1 Col (Mobile) */
gap: 10px;
}
@media (min-width: 600px) {
.responsive-grid {
grid-template-columns: 1fr 1fr;
}
/* 2 Cols */
}
@media (min-width: 900px) {
.responsive-grid {
grid-template-columns: 1fr 1fr 1fr;
}
/* 3 Cols */
}
Output:
4. Showing/Hiding Content
Sometimes you want to show different content on mobile vs desktop.
Code:
.desktop-only {
display: none;
}
@media (min-width: 768px) {
.mobile-only {
display: none;
}
.desktop-only {
display: block;
}
}
Output:
5. Font Clamping (clamp())
Essence: clamp() is a CSS function that
constrains a value between an upper and lower bound. For typography,
it allows text to scale fluidly with the viewport while ensuring it
never gets too small or too big.
Usage: font-size: clamp(min, preferred, max);
The browser will use the preferred value as long as it is
between the min and max.
Calculations:
Example: font-size: clamp(16px, 5vw, 48px);
- Minimum: 16px. The font will never be smaller than this.
- Preferred: 5vw (5% of viewport width). This allows the font
to grow/shrink.
- Maximum: 48px. The font will never be larger than this.
You don't need complex math; let the browser calculate based on the
viewport width!
Tools:
There are many online "Clamp Calculators" that can help you
generate the perfect clamp() formula based on your desired minimum
and maximum pixel sizes and viewport widths.
Reference:
Clamp Calculator (https://clamp.font-size.app/)
Code:
.clamp-text {
font-size: clamp(1rem, 2.5vw, 2rem);
/* Fluid size between 16px and 32px */
}