Samuel laughing

by Samuel Snopko Development

Hidden Treasures of CSS (Part 1)

Hi fellow frontenders! In recent days I really wondered how much great stuff I missed in CSS. I am sure you already heard the phrase "the older I get, the less I know" and this can also be applied to CSS. But enough talking, let's find some treasures!

Samuel laughing

by Samuel Snopko Development

First of all

Yes! I am talking about variables, the holy grail of CSS. But lot of us missed the first one. "CurrentColor" is the keyword controlling color property and I was introduced to it in 2011! So let's keep our code DRY and not repeat ourselves.

Sample code:

.box {
  color: blue;
  border-color: blue;
}
.box::after{
  background-color: blue;
}

DRY code:

.box {
  color: blue;
  border-color: currentColor;
}
.box::after{
  background-color: currentColor;
}

I hope you see the advantages of the DRY code and that you can use it without fear. Browser support is at 97.66% worldwide according to the caniuse.

Dynamic Layout?!

Why not calculate it? The calc() function can really save your a*s, it at least saved mine a few times already. It's a really powerful tool which you can use to prevent div inception or create very nice dynamic layouts. I will write more about it in the future, but it should be part of your tool belt today! Browser support is around 93% worldwide.

Sample code:

.wrapper {
  width: calc(100% - 200px);
}

Link overlay problems

It can be really frustrating to watch your cool design not work properly, because the nice design element lays on the link and user can't click on it. Don't worry, there is a solution, and it's very elegant! You can set the property "pointer-events" on your overlaying element on "none" and it behaves like the element is not there.

See the Pen Pointer Events Sample by Samuel Snopko (@samuells) on CodePen.

Cool, right? But browser support is only at 57%, and it's not because of Microsoft. We have to blame Firefox (already working on it) and Safari!

Reach the bottom

One of our biggest problems - vertical alignment! This is a topic for a whole blogpost, but I would like to share this little trick on how to put an element on the bottom in a wrapper. Look at this sample pen. As you can see the button and content under the button are aligned on the bottom, but no black magic was used. It's just flexbox and margin-top: auto. YES! "Margin-top" set to "auto" and it works as you can see!

.container {
  display: flex;
  flex-direction: column;
}
.end {
  margin-top: auto;
}
<div class="container">
  <p></p>
  <p class="end">aligned on bottom</p>
  <p>aligned on bottom</p>
</div>

Just four secrets and so many words? I hope you learned something and if you liked it, don't worry, this was only the first part. I already picked another 8 hidden treasures from CSS and hopefully I am writing second part right now!