Day 2 - Responsive Design

Try This: Resize your browser window width to see how the examples below adapt!

1. Viewport Units (vw, vh)

vw (viewport width) is relative to the browser window size.
% (percentage) is relative to the parent element size.

Code:

/* CSS */
.vw-box {
    width:  50vw; /* 50% of screen width */
}

.pct-box {
    width:  50%; /* 50% of parent width */
}

Output:

50vw (Half Screen Width)
50% (Half Parent Width)

2. Media Queries (@media)

Style changes based on conditions like screen width. This is the core of responsive design.

Code:

/* CSS */
.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:

Resize me! (Red -> Blue -> Green)

3. Responsive Layouts

Using Grid or Flexbox with media queries to change column counts.

Code:

/* CSS */
.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:

Card 1
Card 2
Card 3
Card 4
Card 5
Card 6

4. Showing/Hiding Content

Sometimes you want to show different content on mobile vs desktop.

Code:

/* CSS */
.desktop-only {
    display:  none;
}

@media (min-width: 768px) {
    .mobile-only  {
        display: none;
    }
    .desktop-only  {
        display: block;
    }
}

Output:

📱 You are on a smaller screen.
💻 You are on a larger screen.

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:

/* CSS */
.clamp-text {
    font-size:  clamp(1rem, 2.5vw, 2rem); /* Fluid size between 16px and 32px */
}

Output:

Resize the browser to see me scale fluidly!