Back to blog

10 Common mistakes in CSS

10 Common mistakes in CSS

Here are some common mistakes that most web developers make, and how identifying and avoiding them can help you write better and more efficient CSS.

1. Use Shorthand

CSS shorthand is a group of CSS properties that allow values of multiple properties to be set simultaneously. These values are separated by spaces. For example, the border property is shorthand for the margin-top, margin-right, margin-left and margin-bottom properties.

//Not Using Shorthand .example{ margin-top:10px; margin-bottom:19px; margin-left:10px; margin-right:19px; } //Better way .example{ margin:10px 19px; }

2. Responsive design

If your website becomes responsive, avoid using the

px
unit. Instead, use percentages.

//Not correct way .container{ width:1000px; } //correct way for responsive .container{ width:100%; }

3. Repeating the Same Code

Reduce duplicated code by grouping similar classes and adding supplementary properties as needed.

//Not correct .box1{ width:50%; margin:20px; } .box2{ width:50%; margin:20px; } //Correct .box1,.box2{ width:50%; margin:20px; }

4. No font fallback

Use a fallback font in case the primary font is not loaded or lacks necessary glyphs.

//Not good body{ font-family:Helvetica; } //Good body{ font-family:Helvetica, Arial, Sans-serif; }

5. Using Color Names

Opt for hex color codes over color names for precision.

//Not good .example{ color:green; } //Good .example{ color:#00ff00; }

6. Complicating Selectors

Avoid overly complex selectors. Prefer direct class targeting for clarity and simplicity.

//It is good sometimes, but often overcomplicated header .navigation ul.nav-links{ list-style-type:none; } //Better .nav-links{ list-style-type:none; }

7. Z-Index mistakes

Moderation is key. Avoid using extremely high z-index values.

//Not good .modal-container{ z-index:545; } .modal{ z-index:5345345; } //Better .modal-container{ z-index:1; } .modal{ z-index:2; }

8. Inconsistency names

Keep naming consistent, reflecting the content or functionality.

.header{ font-size:2rem; }

9. When to use class and Id

Choose classes for design and IDs for unique element targeting.

//ID usage let name = document.getElementById('name').value; console.log(name); //Class usage Paragrah .classData{ margin:20px }

10. Ignoring Cross-Browser Compatibility

Test CSS across different browsers. Consult caniuse.com to verify property compatibility.

Conclusion

In conclusion, avoiding common mistakes in CSS (Cascading Style Sheets) is crucial for creating well-designed and efficient web pages. CSS plays a significant role in controlling the visual presentation and layout of web content. By steering clear of these mistakes, you can ensure your CSS code is clean, maintainable, and compatible across different browsers and devices.

Disclaimer this article was writen by AI for demo purposes only.