Coding better CSS
Be semantic
It is bad when you use selectors that doesn't mean anything in your code, it makes your code messier, difficult to mantain and hard to see where you can reuse.
// bad
.dummy-class {
position: relative;
top: 15px;
}
// good
.article {
position: relative;
top: 15px;
}
Merge same rules
If you see that the same rules are being applied to different selectors, search for a way that you can merge these two selectors.
// bad
#header.green {
background-color: green;
font-size: 12px;
margin: 20px;
}
#header.red {
background-color: red;
font-size: 12px;
margin: 20px;
}
// good
#header {
font-size: 12px;
margin: 20px;
}
.green {
background-color: green;
}
.red {
background-color: red;
}
Find a standard structuring way for your css properties
I found a couple days a go in an article a good way to structure my CSS rules inside a selector, feel free to comment if you think there is a better way.
.class {
/* Positioning */
position: absolute;
z-index: 10;
top: 0;
right: 0;
/* Display & Box Model */
display: inline-block;
overflow: hidden;
box-sizing: border-box;
width: 100px;
height: 100px;
padding: 10px;
border: 10px solid #333;
margin: 10px;
/* Color */
background: #000;
color: #fff
/* Text */
font-family: sans-serif;
font-size: 16px;
line-height: 1.4;
text-align: right;
/* Other */
cursor: pointer;
}
(copied from Idiomatic CSS)
Written by Lucas Rinaldi
Related protips
3 Responses
BEM (Block, Element, Modifier) is also good method for structuring CSS code. Check http://bem.info/method/.
Good turn, Lucas!
I suppose both "left" and "article-left" classes are irrelevant in the way you use them.
<br>- They're a non-semantic. Once your block changes its position, you've to change the class (and find a right template somewhere on backend).
<br>- You've to use !important to overwrite .left and .right classes. This may cause some inheritance issues.
<br>- They're mostly unusable in responsive layouts.
You're totally right, i even broke my first rule, but in my defense it is just like this because it was the first code that came into my mind to explain merging rules. I will think some other better example.
Thanks for adding to the post, i appreciate. :)