CSS:
Good Practices
Cascading selectors
This is good:
.top-bar .header .title {
/* ... */
}
This is bad:
.top-bar-header-title {
/* ... */
}
Specificity
This is good:
.amazing-list a {
/* ... */
}
This is bad:
ul.amazing-list li a {
/* ... */
}
Use class over id
This is less desirable (though a bit faster):
#group {
/* ... */
}
This is good:
.group {
/* ... */
}
Speed benefit lost when combining:
#group .item {
/* ... */
}
border-box all the things
The standard box model is confusing. Use this instead:
html {
/* Default is content-box */
box-sizing: border-box;
}
*,
*:before,
*:after {
box-sizing: inherit;
}
This will make sure padding is accounted for when calculating element size.
Global utility classes
Clutters markup. Avoid if possible:
<div class="bounce flip-vertical align-left">
<!-- ... -->
</div>
Legibility
This is bad:
.header { /* ... */ }
This is good:
.header {
/* ... */
}
More legibility
Grouping properties into logical areas:
.thingymajigg {
position: fixed;
top: 0;
bottom: 0;
left: 0;
right: 0;
display: flex;
flex-direction: column;
background: #000;
color: #fff;
transition: opacity: .5s ease;
}
!important
Using the !important declaration probably means you lost the war on specificity somewhere along the line:
.foo {
/* Override everything! */
color: red !important;
}
.foo .bar {
/* I'm still red :( */
color: green;
}
World War Z
If you know you need lots of layering (z-index), come up with a system:
1-10: Misc.
11-20: Overlays
21-30: Modals
31-40: Tooltips
41-50: ...
Preprocessors (LESS, SASS)
Be aware of the CSS you are producing:
.foo {
.bar {
&.baz {
color: red;
}
}
}
/* Let the war on specificity begin */
.foo .bar.baz {
color: red
}
Excluding older browsers
.thing {
background: white;
}
@media only screen and (width) {
/* Houston, we have CSS3 support */
.thing {
background: papayawhip;
}
}
When you want to create a "good enough" experience for older browsers:
Resets
Don't just set every value to zero. It should make sense:
p {
margin: 0 0 1rem;
}
Measurements
- px
- rem (relative to root element)
- em (relative to parent element)
- % (for elastic sizes)
- vw/vh (relative to viewport)
The End
CSS: Good Practices
By Joacim Löwgren
CSS: Good Practices
Slides on some good practices in CSS.
- 306