After many years of experience with UI and web design i have collected a small but nice list of my favoite CSS hacks that I use on pretty much every project, app or website.
I hope you can learn from this and use it in turn for your projects too.
Add your favorite CSS hacks in the comments below!
- Custom Grid
.grid {
position: relative;
margin: auto;
width: 1200px;
}
@media(max-width: 1200px) {
.grid {
width: 95%;
}
}
This allows you to set a custom grid to work inside and you can edit this grid for different device screen widths.
- Design a custom close icon
.close {
position: absolute;
padding: 5px;
font-style: normal;
font-weight: 600;
transform: scale(1.4);
cursor: pointer;
width: 20px;
height: 20px;
transition: all 0.3s;
z-index: 900;
}
.close::before {
position: absolute;
top: 4px;
left: 12px;
transform: rotate(-43deg);
content: '|';
}
.close::after {
position: absolute;
top: 4px;
left: 14px;
content: '|';
transform: rotate(43deg);
}
I design a custom icon element and wherever i need to use it in my html i simply add this line:
<i class="close"></i>
- CSS Vars
Some CSS can be long and hard to remmeber so i just store it inside a CSS variable and that's it.
:root {
--gradient: linear-gradient(324deg, rgba(119,0,255,1) 0%, rgba(41,4,255,1) 100%);
}
I can then simply call it in my css like this:
.box { background: var(--gradient) }
- Make everything border-box
* {
box-sizing: border-box
}
this way all my elements will be uniform in dimensions and i don't have to worry about padding and borders and whatnot messing up with my widths and heights.
- Get a quick spacer element Sometimes i need to add a quick spacer between elements
.spacer { height: 60px }
And i call it in my html:
<div class="spacer"></div>
- Custom Scrollbars
::-webkit-scrollbar {
width: 10px;
height: 10px;
}
::-webkit-scrollbar-track {
background: #eee;
border-radius: 50px;
}
::-webkit-scrollbar-thumb {
background: green;
border-radius: 50px;
}
That one customizes scrollbars, pretty cool.
- Custom Highlighter
::selection {
background: red;
color: white;
}
- Remove dependency on !important To remove dependencies on !important for cnflicting styles i simply make every selector very specific like:
.app .container .box h1 { color: green; }
Instead of setting styles like
.app h1 {color:green;}
Then if i need a more abstract style definition
i use:
.app h1 { color:green }
.app .container .box h1.title {color:red}
Hope you enjoyed these!
You can add yours in the comments below, i'd love to hear from your!
Top comments (3)
My all time favorite is the Owl selector of Heydon Pickering. It works so well for vertical rhythm in article pages, and its dead simple.
Ah yes I've read about that its pretty cool!
Cool that you share your experience with us. But I see some approaches that is not good for a11y. Please, read more about a11y to improve your code.