ModernCSS.dev

repository·main·Indexed 41 days ago

https://github.com/5t3ph/moderncss-dot-dev

A collection of modern CSS solutions for common layout problems. This resource provides guides on contemporary techniques, including intrinsically responsive grids using repeat(), auto-fit, and minmax(), creating grid-based hero layouts, and simulating container-like behavior using CSS Grid and Flexbox to reduce reliance on viewport-based media queries.

Tokens
28.2K
Snippets
98
Records
118
Agent score
94%

What's inside ModernCSS

  1. Simulate container-like behavior using CSS Grid and Flexbox

    main

    While true Container Queries are an experimental feature, you can achieve similar responsive behaviors (switching from equal-width columns to a row layout) using CSS Grid and Flexbox. These methods allow elements to respond to available space or content width, reducing the reliance on a massive wall of viewport-based media queries.

    Key approaches covered in this guide:

    • Using CSS Grid to manage layout adjustments.
    • Using Flexbox to handle column-to-row transitions.
    • Implementing CSS Custom Properties (Variables) to ensure these solutions are scalable.
    • The "Holy Grail" solution for handling variable-width breakpoint columns.
  2. Compare border, outline, and box-shadow in the CSS Box Model

    main

    When choosing a method to add visual borders, understand how they interact with the CSS Box Model:

    • border: Sits between padding and margin. It is part of the element's computed dimensions, meaning it will impact the layout and size of the element.
    • outline: Sits outside the border, overlapping both box-shadow and margin. It does not affect the element's dimensions.
    • box-shadow: Extends from the edge of the border in defined directions. It does not affect the element's dimensions.

    Use this mental model to decide if you need a method that affects layout (border) or one that is purely visual (outline, box-shadow).

  3. Understand CSS Specificity and the Cascade

    main

    CSS Specificity is a weight applied to a declaration based on the types of selectors used. When multiple declarations target the same element, the one with higher specificity wins. If specificity is equal, the last declaration in the CSS file is applied.

    Key Rules:

    • Directly targeted elements always take precedence over inherited styles.
    • Higher specificity makes rules harder to override.
    • Proper use of specificity and the cascade allows you to avoid using !important.

    Example of Specificity Competition: In the following HTML:

    <div id="specific">
      <span class="item">Item</span>
    </div>

    The color of .item is determined by these rules:

    #specific .item { color: red; }   /* Wins: contains an ID */
    span.item { color: green; }      /* Loski: element + class */
    .item { color: blue; }           /* Loses: class only */
    <div id="specific">
      <span class="item">Item</span>
    </div>
    #specific .item {
      color: red;
    }
    
    span.item {
      color: green;
    }
    
    .item {
      color: blue;
    }
  4. Use :focus-within for advanced interactions

    main

    The :focus-within pseudo-class matches an element if it, or any of its descendants, has received focus. This is useful for styling parent containers when a child input is active (e.g., highlighting a form fieldset when an input inside is focused).

    Note: Use this as a progressive enhancement or with a polyfill, as browser support may vary.

    /* Example: Highlighting a container when a child input is focused */
    .form-group:focus-within {
      border-color: blue;
    }
  5. Choose the right units for `border-radius`

    main

    When setting border-radius, the choice of unit affects how the shape scales:

    • Percentage (%): Relative to the element's size. Note that if the element is not square, 50% will result in an ellipse rather than a circle.
    • Absolute units (px, rem): Preferred for consistent results based on design specifications, regardless of element size.
    • Relative units (vw, em):
      • Viewport units (vw, vh, vmin): Scale with the viewport, providing a consistent rounded appearance across mobile and desktop.
      • em: Scales with the element's font-size, meaning larger text results in larger corner radii.
  6. Understanding the limitations of Media Queries vs. Container Queries

    main

    Traditional Media Queries respond to changes in the viewport size. This creates a problem when elements are nested: a component inside a narrow sidebar might need a different layout than the same component in the main content area, but a media query cannot distinguish between them because it only sees the viewport width.

    Container Queries (an experimental CSS feature) solve this by allowing elements to respond to the size of their parent container rather than the viewport. This allows components to be truly modular and aware of the space available to them, regardless of where they are placed on the page.

  7. Theme form inputs using HSL CSS variables

    main

    Use HSL (Hue, Saturation, Lightness) components in CSS variables to create easily adjustable themes for input states, such as :focus.

    By defining the hue, saturation, and lightness separately, you can programmatically or manually adjust the color of the focus state while maintaining consistent saturation and lightness levels.

    :root {
      --input-border: #8b8a8b;
      --input-focus-h: 245;
      --input-focus-s: 100%;
      --input-focus-l: 42%;
    }
    
    /* Example usage for a focus state */
    .input:focus {
      border-color: hsl(var(--input-focus-h), var(--input-focus-s), var(--input-focus-l));
    }
  8. Create a CSS Grid 'Canvas' for Hero Layouts

    main

    Instead of using position: absolute to layer elements in a hero section, you can turn the container into a single-cell grid 'canvas'. This allows you to position children (like text and images) relative to each other and the container using grid alignment properties, making the layout more responsive and easier to manage.

    1. Set the container to display: grid.
    2. Define a single grid-template-area.
    3. Assign all direct children to that area using the universal selector * and the grid-area property.

    This approach avoids the math and media query headaches associated with absolute positioning when content grows or shrinks.

    header {
      display: grid;
      grid-template-areas: "hero";
    
      > * {
        grid-area: hero;
      }
    }
  9. Maintain accessibility in fluid typography

    main

    When using viewport units (vw) for fluid typography, it is critical to include a relative unit like rem in the preferred value of the clamp() function.

    Using vw alone can prevent users from scaling text via browser zoom, which may violate WCAG Success Criterion 1.4.4: Resize text. By adding 1rem to your scaler (e.g., #{$fluid-scaler} + 1rem), you ensure that the font size responds to both the viewport width and the user's preferred font size/zoom level.

    // Correct pattern for accessible fluid scaling
    font-size: clamp(
      #{$fluid-min}rem,
      #{$fluid-scaler} + 1rem, // Adding 1rem ensures zoom works
      #{$level-size}
    );
  10. How :focus-within enables CSS-only dropdowns

    main

    The :focus-within pseudo-class allows a parent element to be styled when any of its descendants receive focus. This is critical for dropdown menus because it allows the menu to remain visible while a user tabs through the links inside the dropdown.

    Without :focus-within, a standard :focus on the trigger button would be lost as soon as the user moves focus to a link inside the menu, causing the menu to disappear visually.

    Note: For reliable support in older browsers (IE < Edge 79), a polyfill is required.

  11. Compare Flexbox vs. Grid for equal height layouts

    main

    Flexbox

    • Pros: Side-by-side columns are the default behavior (no extra configuration needed for a single row).
    • Cons: Elements are not inherently equal-width; managing a specific number of columns per row requires manual width calculations and flex-wrap: wrap.

    CSS Grid

    • Pros: Elements are inherently equal-width. It is much easier to define a specific number of columns per row using grid-template-columns without complex math.
    • Cons: Requires grid-auto-flow: column to achieve a single row of side-by-side columns.