Unlock the Power of CSS: 6 Golden Nuggets to Simplify Your Code

Smooth Scrolling: A One-Line Wonder

Gone are the days of relying on JavaScript implementations to achieve smooth scrolling. The scroll-behavior property allows us to handle smooth scrolling with just one line of CSS code!

html {
  scroll-behavior: smooth;
}

Browser support is around 75%, and it’s coming to Edge 76 soon.

Dark Mode: A Clever Workaround

Implementing dark mode doesn’t have to be complicated. You can achieve a similar result using mix-blend-mode: difference, one of the blending modes supported on CSS.

body.dark-mode {
  filter: invert(100%);
  background-color: #333;
  mix-blend-mode: difference;
}

This approach eliminates the need to specify inverted colors, and you can isolate the elements you don’t want to change.

Truncate Text: A Native Solution

Meet text-overflow and line-clamp, two CSS properties that can provide a native, easy-to-implement solution for truncating text.

.truncate-text {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.truncate-text multiline {
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

These properties can help you achieve a consistent design across different sizes or resolutions, without relying on JavaScript-based solutions.

Scroll Snapping: Locking the Viewport

CSS scroll snapping is another handy functionality that allows you to create interactions like fullscreen sections, locking the viewport on specific locations as you scroll.

.scroll-snap {
  scroll-snap-type: y mandatory;
  overflow-y: auto;
}

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

With scroll-snap-type and scroll-snap-align, you can achieve this effect natively, without the need for math calculations and JavaScript.

Sticky Navigation: Simplifying Positioning

Sticky positioning is now easier than ever, thanks to the position: sticky property.

.sticky-nav {
  position: sticky;
  top: 0;
}

An element with sticky positioning will behave as a relatively-positioned element until a given point on the viewport is reached, and then become a fixed-positioned element. Browser support is up to 92% with the -webkit prefix.

Bonus: @supports Media-Rule

Even though these CSS features are widely adopted and supported, you might still want to check if they are available on the browser before adding them.

@supports (scroll-behavior: smooth) {
  /* add styles here */
}

The @supports feature query allows you to test if the browser supports a specific property: value pair before applying a set of styles.

By leveraging these CSS golden nuggets, you can simplify your code, reduce your JavaScript bundle, and create compelling UIs that delight your users.

Leave a Reply