开发者

CSS multi-class or groupped class best practices

I new to CSS/CSS3 and I read in many places different way to build CSS files. Some people all tags in the same elements and some people divide elements and then use different classes in the HTML code. eg:

// css

h1 { font: normal 20px Arial; color: black; margin: 1em 0; padding:0; border-bottom: solid 0.1em #ddd; }
h2 { font: normal 16px Arial; color: black; margin: 1em 0; padding:0; border-bottom: solid 0.1em #ddd; }

so in the HTML they just have to put and that's it. If you need to change the border color then you have to change ALL tags that has the border-bottom.

OR

h1 { font: normal 20px Arial; }
h2 { font: normal 16px Arial; }
.colorBlack { color: black; }
.headers { margin: 1em 0; padding:0; }
.borderBottom { border-bottom: solid 0.1em #ddd; }

and in the HTML you use:

<h1 class="black headers borderBottom">h1</h1>

Very easy but eve开发者_开发知识库rytime you have to put all the CSS you need

Is there any Best Practices on how to build CSS? Which way is better for performance or loading time?


I recommend to use:

h1, h2 {
    color: black;
    margin: 1em 0;
    padding: 0;
    border-bottom: solid 0.1em #ddd;
}
h1 {
    font: normal 20px Arial;
}
h2 {
    font: normal 16px Arial;
}

The best practice: Keep your code readable. Readability is not achieved by separating a style definition in several useless classes.

Usually, you want the h1 and h2 tags to have similar styles. For that reason, I've grouped the styles. When you want another property value for a certain element, you can add another CSS definition. When the selector has a higher specificity, the new declaration will override the previous one(s).


I think both technics are useful. Personally I often put two or more classes when I need to separate one element from another (example last in row element should not contain margin-right) my code looks like:

HTML:

<div class="images-row">
    <div class="image-item">...</div>
    <div class="image-item">...</div>
    <div class="image-item">...</div>
    <div class="image-item last-in-row">...</div>
</div>

CSS:

.image-item {
    border:1px solid red;
    margin-right:20px;
    width:200px;
    height:200px;
}

.image-item.last-in-row {
    margin-right:0;
}

(supported well in IE > 7 and other good browsers). This solution keeps the code quite clean and also makes me write less (I don't need to rewrite all the styles for the last element or add separate selectors). jQuery element handling is less confiusing (I need only one selector to match all .image-items).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜