Use HTML tag names, classes or IDs in CSS?

前端 未结 12 1722
攒了一身酷
攒了一身酷 2020-12-14 05:13

In designing the HTML and CSS for a page, when should I use

img.className

versus

.clas

12条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-14 05:31

    You preference should be, in order from highest to lowest:

    1. id

    2. tag
    3. tag.className
    4. .className

    ID selectors are fast. Tag selectors are reasonably fast. Pure class selectors are slow because the browser essentially has to interrogate every element and see if each has that class. Getting elements by ID or tag name are "native" operations from a browser's context.

    Also, I find it good practice to make your CSS selectors as restrictive as possible otherwise it just turns into a mess and you end up getting all sorts of unintended consequences where CSS rules apply where you didn't otherwise expect, which often forces you to create a similar yet different selector just so none of the rules regarding the first don't apply (translating into more mess).

    Basically if you know if you only use a class on div elements then do this

    div.className
    

    not

    .className
    

    If you apply a class to several elements just list them:

    h1.selected, h2.selected, h3.selected
    

    instead of

    .selected
    

    In practice I find very few situations where you need to use "naked" class selectors or where it is advisable to do so.

提交回复
热议问题