Cascading style sheets use “id” or “class”

后端 未结 15 2230
夕颜
夕颜 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:50

    ids

    #header
    #footer
    #sidebar
    #menu
    #content
    

    classes

    .important
    .warning
    .validationError
    .recent
    .outOfDate
    .inactive
    .weekDay
    .previous
    .next
    .first
    .last
    
    0 讨论(0)
  • 2020-12-05 16:50

    Id means identity, it indicates only single tag. It can be use single time on a page.

    Class can be use multiple times. It can be used more than one time in a single page.

    0 讨论(0)
  • 2020-12-05 16:55

    The id attribute is only to be used once within each document. The difference is that you then have a unique id for a specific element within the document, which is handy when scripting, or in fact even for CSS when you need to style specifically only one element.

    Class is more of a "type" delineation. You can specify that an element should have one or more classes, which describe properties about it.

    For instance:

    <div id="header" />
    

    You only have one header on a given document.

    <div class="item alternate last" />
    

    You have multiple items, and this item is one of the alternate items. It is also the last item. You could even give it the id "last" if you know for sure that there is always only one last item in the document.

    Etc.

    0 讨论(0)
提交回复
热议问题