Use HTML tag names, classes or IDs in CSS?

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

    Class selectors

    .className
    

    This is to be used when you have more than one element on the page that you would like to apply the same style to. It can be to any tag element. So in the following all will use the same style as set out by the .className.

    
    

    But you can also restrict it like so:

    img.className
    

    By placing the tag along with the style definition, you're saying that this style is only to be used when it's the class used by that particular tag, in this case, an image.

    HTML code will look like this:

    
    

    If you have other elements on the page using the same class style, but are not of the same tag, then the styles set out in this will not be applied and they will take on the more generic version as mentioned in the first example.

    So repeating the example above:

    
    

    Only the image will take on the style as set out by img.className whereas all the rest will take on the style rules set in .className.

    ID selectors

    #idName
    

    This is to be used when there is only one instance of a particular element that you wish to apply the style to.

    You can also force it to apply only in certain tag conditions as you have earlier with the class definitions.

    p#idName
    

    This example will only apply to the paragraph block marked with the ID:

    If you were to put that id on another element, like this:

    Then it will not take on the style set out and be ignored.

提交回复
热议问题