5 common CSS mistakes to avoid

banner

Let's be real here.

Is CSS that hard?

Even though being simple and uses the modern English language to name most of its properties like font size or color, it's not rare to get caught up in the style classes when you're working on a bigger and high-performance project.

Today, let us discuss 5 common CSS mistakes we all make.

1️⃣ AVOID MAGIC NUMBERS

A magic number is a numerical value that is used simply because it works. Never use numbers simply because they work.

In this case, it's preferable to use top: 100%, which roughly translates to 'all the way from the top.'

Don't do this

1
.dropdown-container
2
.dropdown-menu {
3
4
margin-top: 47px;
5
}

Do this

1
.dropdown-container
2
.dropdown-menu {
3
4
top: 100%
5
}

2️⃣ Avoid mixing container with content styles

On isolated components, don't use location-dependent styles. A component should have the same appearance no matter where it is placed. Instead, for specialized use scenarios, use layout wrappers.

Don't do this

1
.form-input {
2
font-size: 14px;
3
padding: 4px 8px;
4
/*Content is mixed with container here*/
5
margin-top: 20px;
6
}

Do this

1
.form-input-wrapper {
2
margin-topp: 20px;
3
}
4
5
.form-input {
6
font-size: 14px;
7
padding: 4px 8px;
8
}

3️⃣ AVOID USING QUALIFIED SELECTORS

These are selections that are appended to an element unnecessarily. This is bad news because it completely prevents reusability on another element while also increasing specificity.

Don't do this

1
ul.nav {}
2
a.button {}
3
div.header {}

Do this

1
.nav {}
2
.button {}
3
.header {}

4️⃣ AVOID USING ABSOLUTE VALUES FOR LINE-HEIGHT

To make lines more flexible, line heights should always be specified relative to one another. You want to know that if you change the font size of a h1, your line-height will keep up.

Don't do this

1
h1 {
2
font-size: 24px;
3
line-height: 32px;
4
}
5
6
.site-title {
7
font-size: 36px;
8
line-height: 48px;
9
}

Do this

1
h1 {
2
font-size: 24px;
3
line-height: 1.333;
4
}
5
6
.site-title {
7
font-size: 36px;
8
}

5️⃣ AVOID LOOSE CLASS NAMES

Loose class names are awful because you can't tell what they're for by looking at them, and they're so general that another developer could simply redefine them.

Don't do this

1
.card {}
2
.modal {}
3
.user {}

Do this

1
.user-post-card {}
2
.confirmation-modal {}
3
.user-avatar {}

Thank you for reading

If you liked this post, follow me on Twitter for daily threads on web dev resources.

Liked this article? Share it with your network on Linkedin. Have a question, feedback or simply wish to talk to me? Shoot me a DM or send me an email and I'll get back to you as soon as possible.

Have a great one.

– Abhiraj