Cascading style sheets use “id” or “class”

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

    ID's must be unique within a document. CLASS can be applied (and combined) to mutiple elements on the same page.

    ID's cannot be combined (mutiple id's). This works:

    blah blah blah

    but this does not work:

    blah blah blah

    Dynamic HTML typically uses id's to control elements. Elements with id's have the fastest 'lookup', as cletus mentions, when javascript is used in some way to have the page interact with the user.

    Think of class and id in these contexts and the reasons for each become clear.

    Imagine a page with a few functional divs. Every div would have the same class to display a common style (i.e. width). And every div needs a unique id to style it when it has been selected. In this situation, you might have something like this:

    blah blah blah

    and a javascript routine somewhere like:

    function action() 
    {
      document.getElementById( 'div1' ).style.backgroundColor = 'red'
    }
    

    Note: This is dumb code but it is to get the point across

    An element can be unique on each web page but be common to a web site. Thus it makes sense to use class in this context even if it is unique on the page.

    So, a general rule of thumb - if it's unique, use id, if it's not use class. It's really easy to change id to class if needed. It's not as easy to switch back.

提交回复
热议问题