6. Use :not() and :has() Selectors to Simplify Your CSS

Selectors are the backbone of CSS, and the :not() and :has() pseudo-classes can revolutionize how you style elements.

  • :not() Example: Style all buttons except the first one:
button:not(:first-child) {
  background-color: #f0f0f0;
}
  • :has() Example: Style all buttons that contain an SVG icon:
button:has(svg) {
  padding-left: 20px;
}

These selectors make your CSS more powerful by letting you target elements based on their content or siblings, reducing the need for extra classes.

7. Add Gradients to Text with CSS

Who doesn’t love a little gradient? But did you know you can apply gradients to text, not just backgrounds? The trick is to use the background-clip property.

Example:

.gradient-text {
  background: linear-gradient(45deg, #ff6b6b, #feca57);
  -webkit-background-clip: text;
  color: transparent;
}

With background-clip: text;, the background gradient becomes the text color. Add a transparent color property, and boom—gradient text!

8. Create Smooth Dropdown Menus with CSS

Dropdown menus usually rely on JavaScript, but you can create smooth dropdowns using CSS only, thanks to the :focus-within pseudo-class.

Example:

.dropdown:focus-within .menu {
  display: block;
}

By applying :focus-within to the dropdown container, you can show and hide menu items when interacting with the dropdown, all without a single line of JavaScript.

9. Auto-Number Headings with CSS Counters

Want to automatically number your headings without hardcoding them? CSS counters have got you covered!

Example:

body {
  counter-reset: section;
}
h2::before {
  counter-increment: section;
  content: "Section " counter(section) ". ";
}

With this setup, your headings will be numbered automatically, and the numbering will update dynamically as you add or remove sections. Perfect for dynamically generated content.

10. Snap to Elements with Scroll Snap

When building a swiper or any horizontally scrollable container, you can use the scroll-snap-type property to ensure elements snap into place smoothly.

Example:

.wrapper {
  scroll-snap-type: x mandatory;
}
.card {
  scroll-snap-align: center;
}

This creates a magnetic effect, ensuring that elements snap perfectly into view as you scroll. You can even use scroll-snap-type: proximity; to add a more subtle snapping effect.

Final Thoughts

CSS is an incredibly powerful tool for web development, and these tips and tricks will help you take your designs to the next level. Whether you’re building interactive elements, enhancing your layouts, or adding stunning visual effects, there’s always a new CSS technique to explore. So go ahead and try these out in your next project, and don’t forget to share your favorite CSS tricks in the comments below!

1 2
Share.

I am a Full-Stack Web Developer & Security Analyst from Bangladesh. I have built web/online applications on various Open Source Stacks and love information security testing.

Leave A Reply