Use HTML tag names, classes or IDs in CSS?

前端 未结 12 1714
攒了一身酷
攒了一身酷 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:55

    When to use what depends on what you want to select. img.className (type selector + class selector) selects only IMG elements that’s in the class “className” while .className (just class selector) selects any element that’s in that class and #idName (id selector) any element with the ID “idName”.

    But besides that, the selector all have a differente specificity that affects the order in which the properties of that rules overwrite the one of others.

    So if you have an IMG element with the ID “idName” that’s in the class “className”:

    
    

    The properties of the rules would be applied in the following order (specificity from highest to lowest):

    1. #idName
    2. img.className
    3. .className

    But when you use a specific class only for one specific type of elements (e.g. “className” only for IMG element), you can go with only .className.

提交回复
热议问题