DEV Community

Cover image for 10 CSS Tricks for UI developers
Niraj Narkhede
Niraj Narkhede

Posted on

10 CSS Tricks for UI developers

Introduction: Elevating Your CSS Game

Hey there, fellow UI developers! Are you ready to take your CSS skills to the next level? Whether you're a seasoned pro or just starting out, we've all faced those moments when our stylesheets seem to have a mind of their own. But fear not! I've got some nifty CSS hacks up my sleeve that are sure to make your life easier and your designs more impressive.

In this blog post, we're going to explore 10 awesome CSS hacks that will help you solve common design challenges, improve your workflow, and add some extra pizzazz to your projects. These aren't just any old tricks – they're practical, powerful, and perfect for UI developers like us who want to create stunning web experiences.

So, grab your favorite beverage, get comfy, and let's dive into the world of CSS hacks!

1. The Magic of CSS Variables

What Are CSS Variables?

First up on our list of CSS hacks is the use of CSS variables, also known as CSS custom properties. If you haven't started using these yet, you're in for a treat!

CSS variables allow you to store specific values and reuse them throughout your stylesheet. This is especially helpful when you're working with colors, fonts, or any values that you find yourself repeating often.

How to Use CSS Variables

Here's a quick example of how you can set up and use CSS variables:

:root {
  --main-color: #3498db;
  --secondary-color: #2ecc71;
  --font-size: 16px;
}

.button {
  background-color: var(--main-color);
  font-size: var(--font-size);
}

.header {
  color: var(--secondary-color);
}
Enter fullscreen mode Exit fullscreen mode

The Benefits

  • Easy to update: Change the value in one place, and it updates everywhere.
  • Improves readability: Makes your CSS more semantic and easier to understand.
  • Supports theming: Great for creating light and dark modes or multiple color schemes.

2. The Power of the ::before and ::after Pseudo-elements

Understanding Pseudo-elements

Next up in our CSS hacks arsenal are the ::before and ::after pseudo-elements. These little gems allow you to add content to an element without adding extra HTML markup.

Practical Uses

You can use these pseudo-elements for all sorts of cool effects:

  • Adding decorative elements
  • Creating tooltip-like info bubbles
  • Generating content dynamically
  • Creating complex layouts

Example: Creating a Quote Block

Here's a simple example of how you can use ::before and ::after to create a stylish quote block:

blockquote {
  position: relative;
  padding: 20px;
  background: #f9f9f9;
}

blockquote::before,
blockquote::after {
  content: '"';
  font-size: 50px;
  position: absolute;
  color: #ccc;
}

blockquote::before {
  top: 0;
  left: 10px;
}

blockquote::after {
  bottom: -20px;
  right: 10px;
}
Enter fullscreen mode Exit fullscreen mode

3. Flexbox: Your Layout Best Friend

The Flexibility of Flexbox

Flexbox is not exactly a hack, but it's such a powerful tool that it deserves a spot on this list. If you're not using Flexbox yet, you're missing out on one of the most flexible and efficient ways to create layouts in CSS.

Key Flexbox Properties

  • display: flex; - Turns an element into a flex container
  • flex-direction - Controls the direction of flex items
  • justify-content - Aligns items along the main axis
  • align-items - Aligns items along the cross axis

A Simple Flexbox Layout

Here's a quick example of how you can use Flexbox to create a responsive layout:

.container {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
}

.item {
  flex: 0 1 calc(33.333% - 20px);
  margin: 10px;
}

@media (max-width: 768px) {
  .item {
    flex: 0 1 calc(50% - 20px);
  }
}

@media (max-width: 480px) {
  .item {
    flex: 0 1 100%;
  }
}
Enter fullscreen mode Exit fullscreen mode

This creates a flexible grid that adjusts from three columns to two, then to one column as the screen size decreases.

4. The CSS Grid Revolution

Grid vs. Flexbox

While Flexbox is great for one-dimensional layouts, CSS Grid takes it to the next level with two-dimensional layouts. It's perfect for creating complex page structures with ease.

Basic Grid Setup

Here's how you can set up a simple grid:

.grid-container {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-gap: 20px;
}

.grid-item {
  background-color: #f0f0f0;
  padding: 20px;
  text-align: center;
}
Enter fullscreen mode Exit fullscreen mode

Advanced Grid Techniques

You can get really creative with Grid by using named grid areas:

.grid-container {
  display: grid;
  grid-template-areas:
    "header header header"
    "sidebar main main"
    "footer footer footer";
  grid-gap: 20px;
}

.header { grid-area: header; }
.sidebar { grid-area: sidebar; }
.main { grid-area: main; }
.footer { grid-area: footer; }
Enter fullscreen mode Exit fullscreen mode

This creates a layout with a header, sidebar, main content area, and footer, all with just a few lines of CSS!

5. Mastering CSS Transitions

Smooth Moves with Transitions

CSS transitions allow you to change property values smoothly over a given duration. They're a great way to add subtle animations to your UI elements without the need for JavaScript.

Basic Transition Syntax

The basic syntax for a transition is:

.element {
  transition: property duration timing-function delay;
}
Enter fullscreen mode Exit fullscreen mode

Practical Example: Button Hover Effect

Let's create a simple button with a smooth color change on hover:

.button {
  background-color: #3498db;
  color: white;
  padding: 10px 20px;
  border: none;
  transition: background-color 0.3s ease;
}

.button:hover {
  background-color: #2980b9;
}
Enter fullscreen mode Exit fullscreen mode

This creates a button that smoothly changes color when you hover over it, providing a nice visual feedback to the user.

6. The Magic of CSS Shapes

Breaking Out of the Box

CSS Shapes allow you to create non-rectangular layouts, which can add a unique and interesting look to your designs.

Using shape-outside

The shape-outside property defines a shape around which inline content should wrap. Here's an example:

.circle-shape {
  width: 200px;
  height: 200px;
  float: left;
  shape-outside: circle(50%);
  clip-path: circle(50%);
  background: #3498db;
}
Enter fullscreen mode Exit fullscreen mode

This creates a circular shape that text will wrap around, creating a visually interesting layout.

Combining Shapes with Images

You can also use shape-outside with images to create even more complex shapes:

.image-shape {
  float: left;
  shape-outside: url('path-to-your-image.png');
}
Enter fullscreen mode Exit fullscreen mode

This allows the text to flow around the contours of your image, creating a seamless integration of text and visuals.

7. The Power of CSS Counters

Automatic Numbering with CSS

CSS counters are like variables maintained by CSS whose values can be incremented by CSS rules. They're great for creating numbered lists or sections without the need for extra markup.

Setting Up Counters

Here's how you can set up and use a counter:

body {
  counter-reset: section;
}

h2::before {
  counter-increment: section;
  content: "Section " counter(section) ": ";
}
Enter fullscreen mode Exit fullscreen mode

This will automatically number your h2 elements with "Section 1:", "Section 2:", and so on.

Nested Counters

You can even create nested counters for sub-sections:

body {
  counter-reset: section;
}

h2 {
  counter-reset: subsection;
}

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

h3::before {
  counter-increment: subsection;
  content: counter(section) "." counter(subsection) " ";
}
Enter fullscreen mode Exit fullscreen mode

This creates a numbering system like "1.1", "1.2", "2.1", etc., for your sections and subsections.

8. Custom Scrollbars with CSS

Styling the Scrollbar

Did you know you can style scrollbars using CSS? While this doesn't work in all browsers, it can add a nice touch to your design in supported browsers.

Webkit Scrollbar Styling

Here's an example of how to style scrollbars in webkit browsers:

::-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 creates a custom scrollbar with a gray thumb that darkens on hover.

Cross-Browser Scrollbar Styling

For a more cross-browser compatible solution, you can use the new scrollbar-color and scrollbar-width properties:

* {
  scrollbar-width: thin;
  scrollbar-color: #888 #f1f1f1;
}
Enter fullscreen mode Exit fullscreen mode

This sets a thin scrollbar with a gray thumb and light gray track across browsers that support these properties.

9. CSS-only Tooltips

No JavaScript Required!

Tooltips are a great way to provide additional information without cluttering your UI. And guess what? You can create them using just CSS!

Basic CSS Tooltip

Here's a simple CSS-only tooltip:

.tooltip {
  position: relative;
  display: inline-block;
  border-bottom: 1px dotted black;
}

.tooltip .tooltiptext {
  visibility: hidden;
  width: 120px;
  background-color: black;
  color: #fff;
  text-align: center;
  border-radius: 6px;
  padding: 5px 0;
  position: absolute;
  z-index: 1;
  bottom: 125%;
  left: 50%;
  margin-left: -60px;
  opacity: 0;
  transition: opacity 0.3s;
}

.tooltip:hover .tooltiptext {
  visibility: visible;
  opacity: 1;
}
Enter fullscreen mode Exit fullscreen mode

To use this, you would structure your HTML like this:

<div class="tooltip">Hover over me
  <span class="tooltiptext">Tooltip text</span>
</div>
Enter fullscreen mode Exit fullscreen mode

This creates a tooltip that appears when you hover over the text, with a smooth fade-in effect.

10. CSS-only Accordion

Expandable Content Without JavaScript

Our final CSS hack is a nifty accordion effect that doesn't require any JavaScript. This is great for FAQ sections or any content that you want to expand and collapse.

The CSS-only Accordion

Here's how you can create a CSS-only accordion:

.accordion {
  max-width: 500px;
  margin: 0 auto;
}

.accordion-item {
  border-bottom: 1px solid #ddd;
}

.accordion-header {
  display: block;
  padding: 15px;
  background-color: #f4f4f4;
  color: #333;
  text-decoration: none;
  position: relative;
  cursor: pointer;
}

.accordion-header::after {
  content: '+';
  position: absolute;
  right: 15px;
  top: 50%;
  transform: translateY(-50%);
}

.accordion-content {
  max-height: 0;
  overflow: hidden;
  transition: max-height 0.3s ease-out;
}

.accordion-item input[type="checkbox"] {
  display: none;
}

.accordion-item input[type="checkbox"]:checked ~ .accordion-content {
  max-height: 1000px;
}

.accordion-item input[type="checkbox"]:checked ~ .accordion-header::after {
  content: '-';
}
Enter fullscreen mode Exit fullscreen mode

And here's the HTML structure:

<div class="accordion">
  <div class="accordion-item">
    <input type="checkbox" id="item1">
    <label class="accordion-header" for="item1">Section 1</label>
    <div class="accordion-content">
      <p>Content for section 1...</p>
    </div>
  </div>
  <!-- Repeat for more accordion items -->
</div>
Enter fullscreen mode Exit fullscreen mode

This creates an expandable accordion that works purely with CSS, no JavaScript required!

Conclusion: Mastering CSS Hacks

And there you have it, folks! We've journeyed through 10 awesome CSS hacks that can really elevate your UI development game. From the flexibility of CSS variables to the magic of pseudo-elements, from layout masters like Flexbox and Grid to purely CSS-driven interactive elements like tooltips and accordions, these techniques offer a wealth of possibilities for creating engaging and efficient user interfaces.

Top comments (44)

Collapse
 
alex__ca638de1ec30 profile image
Alex Maltsev

Why are common things called tricks and hacks?

Collapse
 
mark_kimitch_b168cb8241ef profile image
Mark Kimitch

For the clicks... obvi.

Collapse
 
spiritfox358 profile image
spiritfox358

hahaha, I also have same doubt

Collapse
 
nnnirajn profile image
Niraj Narkhede

Its Depends upon experience, for beginners its Tricks, for experienced its common things.

Collapse
 
johnmunsch profile image
John Munsch • Edited

Good article. I recognize that you're probably constrained by what you can show on a page on Dev.to, but maybe next time screenshots of the applied styles accompanying each would be great or even a link to an interactive page deployed to GitHub or one of the online sandbox sites would give it even more pizzaz.

Collapse
 
nnnirajn profile image
Niraj Narkhede

Thanks ! I am glad you like it.

Collapse
 
kirit_makwana_85d93c0ed13 profile image
kirit makwana

Yes, Better to provide a link for demo of the snippets

Collapse
 
nnnirajn profile image
Niraj Narkhede

Sure

Collapse
 
melnik909 profile image
Stas Melnikov

Hey @nnnirajn!

A lot of pure CSS solutions have huge problems. For example, pure CSS tooltips from your article.

The :hover pseudo-class matches when user hover on an interactive element. But it stops matches immediately when users make the cursor away.

Users with tremor will see infinite flashing. It's why the good solutions is to add a few seconds delay with JS.

Collapse
 
nnnirajn profile image
Niraj Narkhede

Thanks for the suggestion !!

Collapse
 
hbthepencil profile image
HB_the_Pencil

This is a neat article, but I wish there was a bit more detail, especially at the beginning (things like Flexbox don't have a ton of documentation in the article). Overall, though, these are good tips, and I would love to use the tooltips especially someday.

Collapse
 
nnnirajn profile image
Niraj Narkhede

I am glad you like it !!

Collapse
 
kdankov profile image
Konstantin Dankov

No need for the input trick for accordion anymore. We have details and summary tags with name attribute to manage open state across multiple elements. It is also possible to do native css animations on height and display properties

Collapse
 
thefinn15 profile image
Timur

Dude, why most of things in the article its common "tricks" from similar articles as "How to learn CSS in 2024 for beginners" ? And why you aren’t talking about media queries or custom select input with cross-browsing ? If we are talking about "super advanced tricks hacks" 😂

Collapse
 
nnnirajn profile image
Niraj Narkhede

I will try to write an detailed article on media queries and custom select input with cross-browsing.

Collapse
 
shikkaba profile image
Me

This article isn't really tricks. These are all common CSS.

Collapse
 
nnnirajn profile image
Niraj Narkhede

Its Depends upon experience, for beginners its Tricks, for experienced its common things.

Collapse
 
john_smithappdev_5a63a71c profile image
John smithappdev

"Wow, this is an incredibly well-structured and insightful post! Thank you for sharing such practical CSS tricks – I especially loved the sections on CSS variables and Flexbox. They’re such game-changers for simplifying and maintaining stylesheets.

The example with the pseudo-elements for a quote block is so creative – I've been meaning to experiment with them more. The CSS-only accordion idea is also brilliant! It's amazing how much can be achieved without JavaScript these days.

Do you have any favorite resources or tools for experimenting with CSS shapes or creating cross-browser custom scrollbars? Those are areas I’d love to dive deeper into.

Thanks again for this amazing breakdown. Looking forward to seeing more from you!"

Collapse
 
nnnirajn profile image
Niraj Narkhede

Thank you so much for your comment !!

Collapse
 
procoders profile image
ProCoders

Thank you!

Collapse
 
mkastner profile image
mtkastner

For accordion you can use summary and detail tags which also make for better semantics and accessibility.

Collapse
 
nnnirajn profile image
Niraj Narkhede

Yup we can use detail tags also

Collapse
 
madeinmilwaukee profile image
Chuck Watson • Edited

I agree, there is no need to "hack" with css. See the spec

Thread Thread
 
nnnirajn profile image
Niraj Narkhede

Its Depends upon experience, for beginners its Tricks, for experienced its common things.

Collapse
 
nnnirajn profile image
Niraj Narkhede

I am glad you like it

Collapse
 
fredg_prod profile image
Frédéric G. (FredG_ProD)

A great cheat sheet !

Collapse
 
nnnirajn profile image
Niraj Narkhede

Thank you !!

Some comments may only be visible to logged-in visitors. Sign in to view all comments.