Cascading style sheets use “id” or “class”

后端 未结 15 2434
夕颜
夕颜 2020-12-05 16:11

when styling specific html elements, i tend to always use the class attribute. the css code looks cleaner imo.

why do both exist which one should you use and when ?<

15条回答
  •  南方客
    南方客 (楼主)
    2020-12-05 16:34

    There are many ways of selecting a style. You can use id's, classes and tags, and you can combine them:

    #nav - applies to the element with id="nav"

    #nav div - applies to any div element inside the element with id="nav"

    #nav .left - applies to any element with class="left" inside the element with id="nav"

    .item span - applies to any span element inside the element with class="item"

    .item .address - applies to any element with class="address" inside the element with class="item"

    div.item - applies to any div element with class="item"

    #nav div span - applies to any span element inside a div element inside the element with id="nav"

    Important for css selectors is how specific they are. An id is more specific than a class. With this style:

    .dark { color: black; }
    #bright { color: white; }
    

    This element would get white text, as the style using the id is more specific than the style using the class:

    Hello world

    There is even more to know about selectors and specificity. I have found this tutorial to be a good overview of selectors: Selectutorial

提交回复
热议问题