CSS多类或分组类最佳实践 [英] CSS multi-class or groupped class best practices

查看:90
本文介绍了CSS多类或分组类最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是CSS/CSS3的新手,在许多地方,我以不同的方式阅读了构建CSS文件的方法.有些人将标签全部放在同一元素中,有些人将元素分开,然后在HTML代码中使用不同的类. 例如:

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; }

因此在HTML中,它们只需要放置就可以了.如果需要更改边框颜色,则必须更改所有带有边框底部的标签.

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; }

,并在HTML中使用:

and in the HTML you use:

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

非常容易,但是每次都要放置所需的所有CSS

Very easy but everytime you have to put all the CSS you need

是否有关于构建CSS的最佳实践?哪种方法对性能或加载时间更好?

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

推荐答案

我建议使用:

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.

通常,您希望h1h2标签具有相似的样式.因此,我对样式进行了分组.当您想要某个元素的另一个属性值时,可以添加另一个CSS定义. 选择器具有更高的特异性时,新的声明将覆盖以前的声明.

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).

这篇关于CSS多类或分组类最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆