4 CSS tricks that will get you dirty looks from other developers

cydstumpel

Cyd

Posted on January 10, 2020

4 CSS tricks that will get you dirty looks from other developers

Dirty tricks in CSS are very useful; where would YouTube players be without using padding–bottom: 56.25% to create a 16:9 ratio? I assembled a list of my favourite dirty tricks for you!

1. Min margins

This one gets me a lot of dirty looks, but that doesn't mean it's wrong.
If you add items that vary in width in a row with a (quite large) gap in between it can be very hard to determine when those items won't fit on the same row anymore, using a margin on only one side can also mess with centered items or make items break too soon.

.row {
  display: flex;
  flex-wrap: wrap;
  margin: 0 -2rem;
}

.column {
  margin: 10px 2rem 0; // ensures a 4rem gap between items
}
Enter fullscreen mode Exit fullscreen mode

2. Extending the clickable area

I've talked about this in a previous article, because pseudo elements like ::before on an anchor tag (<a>) inherit the click-ability of its parent you can use it to extend the clickable area of a link.

Make sure you add position: relative on the element you want to use as reference for the clickable area.

In the following example I used position: relative to the entire .list-item and position: absolute to the pseudo element with either top, left, right & bottom set to 0, or width: 100%; height: 100%;

Some developers would add an anchor link around the entire list item, this is really annoying to people using screen readers. It's also annoying to style, because you'd have to set the text-transform and color property to overwrite standard link behaviour on all text.

This trick works on buttons as well🤓

3. Writing mode

Writing mode is a css property used to set the writing direction. This is of course meant for languages that have a different writing direction than left to right, it's also very useful to style text that has been rotated 90deg.
When you use transform to rotate text 90deg padding-left will appear on the top of the element (which is probably what you would expect) but the container also gets a weird width; see the codepen below when you click on the texts. You won't get this with writing-mode: vertical-lr;. The big downside of using writing mode instead of transforms is that you can't animate the rotation between two writing modes.

4. Padding bottom

For some reason when you use percentages for padding-bottom they are not based on the height of the element but the width. This is very useful in styling YouTube embeds since you probably want it to take up 100% of the available width, but you can't always be exactly sure how wide that space is. Using height: 56.25% (16/9) won't work, but adding padding-bottom: 56.25% will!

💖 💪 🙅 🚩
cydstumpel
Cyd

Posted on January 10, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related