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

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.

主站蜘蛛池模板: 八宿县| 枝江市| 平武县| 华容县| 南京市| 鲁甸县| 教育| 广州市| 石楼县| 类乌齐县| 靖西县| 天峻县| 河北省| 江西省| 西峡县| 龙里县| 丰顺县| 罗平县| 浪卡子县| 新密市| 汤阴县| 上思县| 安岳县| 泸西县| 四会市| 登封市| 陈巴尔虎旗| 乐安县| 沾化县| 全南县| 海伦市| 中卫市| 武穴市| 东山县| 德保县| 庆元县| 碌曲县| 泸水县| 郧西县| 长治市| 乐山市|