Dynamic Layouts with CSS :has() without JavaScript

CSS example showing layout change using :has and :checked selectors

Stop using Javascript to change your layout dynamically.

You can do it entirely with CSS.

Here’s how it works:

    1. Use input elements (checkbox or radio) to mimic click actions.
    1. The :has() pseudo-class lets a parent element respond to a child’s state.

—> Example: .container:has(input) .child {}

    1. Use :checked to detect if an input is selected.

—> Example: input[type="radio"]:checked {}

    1. Combine :has() and :checked to target specific states and apply styles dynamically.

—> Example: .container:has(input:checked) .child {}

In the example below, we just change the grid-template-columns values when a specific checkbox has been checked.

You can use this for multiple things like e-commerce product, portfolio galleries, dashboards, blog layout, …

Modern CSS makes it easier than ever to create interactive layouts.

To learn more tips about CSS, make sure to join my newsletter below ❤️

Related Articles

Explore more articles on front-end development, covering HTML, CSS and JavaScript for building high-performance websites.

    No strings attached, unsubscribe anytime!