10 CSS Code Snippets Every UI Developer Should Know

Niraj Narkhede - Oct 22 - - Dev Community

Introduction: Supercharge Your Stylesheets with These Handy CSS Tricks

Hey there, fellow UI developers! Are you ready to add some pizzazz to your stylesheets? We all know that CSS can be both a blessing and a curse. It's incredibly powerful, but sometimes it feels like we're wrestling with a stubborn octopus trying to get our layouts just right. That's why I've put together this collection of 10 small but mighty CSS code snippets that'll make your life easier and your designs shine.

These aren't just any old snippets – they're the kind of tricks that'll have you slapping your forehead and saying, "Why didn't I think of that?" Whether you're a CSS newbie or a seasoned pro, I guarantee you'll find something useful here. So, grab your favorite beverage, fire up your code editor, and let's dive into some CSS magic!

1. The Magical Centering Trick

We've all been there – trying to center a div both vertically and horizontally, and ending up with a tangled mess of floats and margins. Well, say goodbye to those frustrating days because this little snippet is about to become your new best friend:

.center-me {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
Enter fullscreen mode Exit fullscreen mode

This code uses the power of CSS transforms to perfectly center an element within its parent container. Here's how it works:

  1. We set the element's position to absolute, which takes it out of the normal document flow.
  2. We move it 50% from the top and left of its container.
  3. The transform property then shifts the element back by half its own width and height.

The result? Perfectly centered content, every time. No more fiddling with margins or pulling your hair out over uncooperative layouts!

2. Smooth Scrolling for the Win

Want to add a touch of elegance to your page navigation? This snippet will give you buttery-smooth scrolling with just a few lines of code:

html {
  scroll-behavior: smooth;
}
Enter fullscreen mode Exit fullscreen mode

That's it! This simple declaration tells the browser to use smooth animations when scrolling to anchor links on your page. It's a small change that can make a big difference in how polished and professional your site feels.

Pro tip:

If you want to get fancy, you can even customize the scrolling speed with a little JavaScript:

document.documentElement.style.scrollBehavior = 'smooth';
Enter fullscreen mode Exit fullscreen mode

3. The Clearfix Hack: Taming Floated Elements

Floats can be tricky beasts. They have a nasty habit of breaking out of their containers and wreaking havoc on your layouts. Enter the clearfix hack:

.clearfix::after {
  content: "";
  display: table;
  clear: both;
}
Enter fullscreen mode Exit fullscreen mode

Add this class to any container with floated children, and watch as order is restored to your layout. The ::after pseudo-element creates an invisible box after the container's content, which clears the floats and keeps everything nice and tidy.

4. Custom Scrollbars: Because Default is Boring

Who says scrollbars have to be ugly? With this CSS snippet, you can style your scrollbars to match your site's design:

::-webkit-scrollbar {
  width: 10px;
}

::-webkit-scrollbar-track {
  background: #f1f1f1;
}

::-webkit-scrollbar-thumb {
  background: #888;
}

::-webkit-scrollbar-thumb:hover {
  background: #555;
}
Enter fullscreen mode Exit fullscreen mode

This code gives you a sleek, customized scrollbar that works in WebKit-based browsers (like Chrome and Safari). You can adjust the colors and dimensions to fit your design perfectly.

Remember: While this snippet is great for WebKit browsers, other browsers might not support these pseudo-elements. Always test across different browsers to ensure a consistent experience for all users.

5. The Flexbox Centering Shortcut

Flexbox has revolutionized the way we handle layouts in CSS. Here's a quick and dirty way to center content both vertically and horizontally using flexbox:

.flex-center {
  display: flex;
  justify-content: center;
  align-items: center;
}
Enter fullscreen mode Exit fullscreen mode

Apply this class to a container, and all its child elements will be perfectly centered. It's simple, it's powerful, and it works across all modern browsers. What's not to love?

6. Truncate Text with Ellipsis

Sometimes you need to display text in a confined space, but you don't want it to wrap or overflow. This snippet will truncate your text and add an ellipsis (...) at the end:

.truncate {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
Enter fullscreen mode Exit fullscreen mode

This is perfect for keeping your designs clean and preventing long strings of text from breaking your layout. Just be sure to provide a way for users to see the full text if needed, like a tooltip or expandable element.

7. The CSS Triangle: No Images Required

Need a triangle for an arrow or tooltip? Don't reach for Photoshop – you can create one with pure CSS:

.triangle {
  width: 0;
  height: 0;
  border-left: 25px solid transparent;
  border-right: 25px solid transparent;
  border-bottom: 50px solid #333;
}
Enter fullscreen mode Exit fullscreen mode

This creates a triangle pointing upwards. You can adjust the border widths to change the triangle's size and proportions, and modify which borders are colored to change its direction.

Bonus tip:

Want to create other shapes? Check out this nifty CSS shapes generator: CSS Shape Generator

8. Simple CSS Gradient Background

Gradients can add depth and interest to your designs. Here's how to create a simple linear gradient background:

.gradient-bg {
  background: linear-gradient(to right, #ff7e5f, #feb47b);
}
Enter fullscreen mode Exit fullscreen mode

This creates a horizontal gradient from a warm orange to a soft peach. You can adjust the colors and direction to suit your needs. For more complex gradients, check out tools like CSS Gradient to generate the code for you.

9. The Lobotomized Owl Selector

Don't let the weird name scare you – this selector is incredibly useful for adding consistent spacing between elements:

* + * {
  margin-top: 1.5em;
}
Enter fullscreen mode Exit fullscreen mode

This selector targets any element that directly follows another element, adding a top margin. It's a great way to maintain vertical rhythm in your layouts without having to add margin classes to every element.

Be careful with this one! While it's powerful, it can also have unintended consequences if not used thoughtfully. Consider using it on specific containers rather than globally.

10. CSS Variables for Easy Theming

Last but not least, let's talk about CSS variables (also known as custom properties). They're a game-changer for creating flexible, themeable designs:

:root {
  --primary-color: #007bff;
  --secondary-color: #6c757d;
  --font-size: 16px;
}

.button {
  background-color: var(--primary-color);
  font-size: var(--font-size);
}
Enter fullscreen mode Exit fullscreen mode

By defining variables in the :root pseudo-class, you can reuse these values throughout your stylesheet. Need to change your primary color? Just update the variable once, and it'll propagate throughout your entire design.

Putting It All Together: A Real-World Example

Now that we've covered these awesome CSS snippets, let's see how we might use some of them together in a real-world scenario. Imagine we're building a simple card component for a blog post preview:

<div class="card">
  <div class="card-image">
    <img src="blog-post-image.jpg" alt="Blog post feature image">
  </div>
  <div class="card-content">
    <h2 class="card-title truncate">This is a really long blog post title that might overflow</h2>
    <p class="card-excerpt">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam in dui mauris.</p>
    <a href="#" class="card-link">Read More</a>
  </div>
</div>
Enter fullscreen mode Exit fullscreen mode

And here's the CSS to style it, incorporating several of our snippets:

:root {
  --primary-color: #007bff;
  --text-color: #333;
  --background-color: #f8f9fa;
}

.card {
  width: 300px;
  background-color: var(--background-color);
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.card-image img {
  width: 100%;
  height: 200px;
  object-fit: cover;
}

.card-content {
  padding: 20px;
}

.card-title {
  color: var(--text-color);
  margin-bottom: 10px;
}

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

.card-excerpt {
  color: var(--text-color);
  font-size: 14px;
  line-height: 1.5;
  margin-bottom: 15px;
}

.card-link {
  display: inline-block;
  color: var(--primary-color);
  text-decoration: none;
  font-weight: bold;
}

.card-link:hover {
  text-decoration: underline;
}

/* Smooth scrolling for the entire page */
html {
  scroll-behavior: smooth;
}

/* Custom scrollbar */
::-webkit-scrollbar {
  width: 8px;
}

::-webkit-scrollbar-track {
  background: var(--background-color);
}

::-webkit-scrollbar-thumb {
  background: var(--primary-color);
  border-radius: 4px;
}

::-webkit-scrollbar-thumb:hover {
  background: #0056b3;
}

Enter fullscreen mode Exit fullscreen mode

In this example, we've used CSS variables for easy theming, the truncate class to handle long titles, and added smooth scrolling and a custom scrollbar for a polished look. The card layout itself uses flexbox principles for alignment and spacing.

Conclusion: Leveling Up Your CSS Game

And there you have it, folks – 10 small but mighty CSS code snippets that can make a big difference in your development workflow. From solving common layout challenges to adding those little touches of polish, these snippets demonstrate the power and flexibility of CSS.

Remember, the key to becoming a CSS wizard isn't just knowing these tricks – it's understanding when and how to use them. As you incorporate these snippets into your projects, take the time to experiment and understand how they work. Don't be afraid to tweak and combine them to fit your specific needs.

Here are a few final tips to keep in mind as you continue your CSS journey:

  1. Stay curious: The world of CSS is always evolving. Keep an eye out for new properties and techniques that can enhance your toolkit.
  2. Practice, practice, practice: The more you use these snippets, the more intuitive they'll become.
  3. Read the specs: When in doubt, go straight to the source. The official CSS specifications can provide valuable insights into how properties work.
  4. Share your knowledge: Found a cool CSS trick? Share it with your fellow developers! The web development community thrives on shared knowledge and experiences.

So, what are you waiting for? Fire up your favorite code editor and start playing with these snippets. Your stylesheets (and your future self) will thank you!

Happy coding, and may your CSS always be bug-free and beautiful!

. . . . . . . . . . . . . . . . . . . . . . . .