lukedavies.dev

Search by title or category tag

CSS snippets you should know in 2023

Luke Davies

css

23/03/2023

Container Queries

This feature has been sought after for years and its finally now stable across all browsers.

With container queries you can query the styling information of a parent element, such as itsĀ inline-size. With media queries, you could query the size of the viewport, container queries enable components that can change based on where they are in the UI.

We set containment on a parent element by setting container-type or you can use the container shorthand to give it both a type and a name similtaneously.

By setting container-type to inline-size the child queries the inline-direction size (width) of the parent.

.panel {
  container: layers-panel / inline-size;
}

.card {
  padding: 1rem;
}

@container layers-panel (min-width: 20rem) {
  .card {   padding: 2rem;
  }
}

This is fantastic for resuable components, it means you can have the same component display differently on the same screen size depending where its placed. eg in the main content or a narrow sidebar.

Scroll Snap

TheĀ scroll-snap-typeĀ CSS property sets how strictly snap points are enforced on the scroll container in case there is one. Link to Mozilla here.

Swipers and sliders are used in the demos and seem like great ways to implement this style in pure CSS

.snaps {
  overflow-x: scroll;
  scroll-snap-type: x mandatory;
  overscroll-behavior-x: contain;
}

.snap-target {
  scroll-snap-align: center;
}

.snap-force-stop {
  scroll-snap-stop: always;
}

Quick circle

Of all the ways to make a circle in CSS, this is the quickest

.circle {
  inline-size: 25ch;
  aspect-ratio: 1;
  border-radius: 50%;
}

lukedavies.dev 2023