官术网_书友最值得收藏!

Should we use classes or IDs?

Now, you're probably thinking, what's the difference between a class and an ID? Well, the first point to make is an ID has more weight than a class, literally 10 times more weight. Keeping your selectors lightweight is one of the keys to scalable, reusable CSS. What does having more weight really mean? It means it's more specific and an ID will overrule any class. We'll deep dive into specificity rules and weights in Chapter 4, Creating Buttons with Modular, Reusable CSS Classes, and CSS3. For now, just know that IDs will overrule classes when targeting the same element. The second point to make is that an ID is unique, and therefore, it can only be used once per page. Given these two points, primarily the first point, as a coding standard, I rarely use IDs for styling because classes are almost always more than sufficient.

Renaming elements with a simple class is so unbelievably powerful and probably the most useful thing in all of CSS. While naming classes, although sometimes tricky, it is important to make names semantic or meaningful. For example, if you're naming your blog post container, it's okay to name it "blog-post-container" because that perfectly describes what it is. IDs, although they have their time and place, aren't as useful as classes. It's best to just use a class in most circumstances to keep your specificity low. In the next section, you'll learn about how we can target elements by their context using descendant selectors.

主站蜘蛛池模板: 兴宁市| 建昌县| 仪征市| 横山县| 札达县| 武功县| 东乡族自治县| 卢氏县| 南康市| 龙井市| 镇远县| 彭阳县| 平乐县| 合肥市| 礼泉县| 泰来县| 长寿区| 凉城县| 华阴市| 浑源县| 邹城市| 西乌| 汪清县| 贵溪市| 罗定市| 贵溪市| 独山县| 河间市| 菏泽市| 平凉市| 汾阳市| 阿拉善左旗| 阿图什市| 霍邱县| 葫芦岛市| 集安市| 太仆寺旗| 嘉荫县| 偃师市| 长兴县| 金川县|