5 CSS Tricks I Wish I Knew When I Started

Published on: by Dr. Talib

When I started learning CSS, I spent hours fighting with floats, clearing divs, and trying to center things. It was a nightmare. But CSS has come a long way. Here are 5 modern CSS tricks that would have saved me hundreds of hours.

1. The "Holy Grail" of Centering

Forget margin: auto or absolute positioning hacks. If you want to center something perfectly in the middle of a container, just use Grid.

.container {
  display: grid;
  place-items: center;
  height: 100vh;
}

That's it. Two lines of code. It works for text, images, divs, anything.

2. Aspect Ratio (No More Padding Hacks)

Remember the "padding-bottom: 56.25%" hack to make responsive videos? You can delete that from your brain. Now we have a native property.

.video-container {
  width: 100%;
  aspect-ratio: 16 / 9;
}

The browser handles the math for you. It's beautiful.

3. `calc()` is Magic

Sometimes you need a width that is "100% minus 20 pixels". In the old days, you'd use box-sizing and padding and hope for the best. Now, you can just do math.

.sidebar {
  width: 300px;
}
.content {
  width: calc(100% - 300px);
}

You can mix units! Percentages, pixels, rems, vh—it doesn't matter.

4. `gap` for Flexbox

For years, Flexbox was great but annoying because you had to use margins to space items out, which meant you always had to remove the margin from the last item.

/* The Old Way */
.item {
  margin-right: 20px;
}
.item:last-child {
  margin-right: 0;
}

/* The New Way */
.container {
  display: flex;
  gap: 20px;
}

The gap property works exactly like you expect it to. It puts space between items, not around them.

5. Smooth Scrolling

Want that nice sliding effect when a user clicks a "Back to Top" link? You don't need jQuery. You don't even need JavaScript.

html {
  scroll-behavior: smooth;
}

One line of CSS in your global stylesheet and your whole site feels more premium.

Test these out! Open our Live CSS Editor and paste these snippets to see them in action immediately.