Class or ID on Body Tag

前端 未结 6 632
抹茶落季
抹茶落季 2021-01-01 11:40

I\'ve been applying an ID to the body tag of my HTML documents lately to allow greater CSS control (#9). Recently the though occurred to me that I could do exactly the same

相关标签:
6条回答
  • 2021-01-01 11:41

    It is better to use a class if you plan to reuse a style in pages. IDs are good if style sheet is designed for a specific page. But still depends on your app.

    0 讨论(0)
  • 2021-01-01 11:41

    In HTML5, the id attribute can be used on any HTML element (it will validate on any HTML element. However, it is not necessarily useful).

    In HTML 4.01, the id attribute cannot be used with: <base>, <head>, <html>, <meta>, <param>, <script>, <style>, and <title>.

    Note: HTML 4.01 has greater restrictions on the content of id values (for example; in HTML 4.01 id values cannot start with a number).

    Source: W3School

    0 讨论(0)
  • 2021-01-01 11:48

    You can (read: should) only use the id on the body tag.

    ID = single use per page

    Class = multiple uses

    1 Body tag = 1 id tag. This can be the same on different pages. Essentially, using the class tag is probably overkill for this purpose.

    0 讨论(0)
  • 2021-01-01 11:57

    Using a class is perfectly acceptable, possibly more so than using an id. Use of ids should be limited as much as possible, because they can clash with other ids and break things like document.getElementById.

    An id selector is more specific than a class selector, which usually makes it a better choice for your use case. -- David Dorward

    However, a high "specificness" is not always desirable. Consider body#faq #col_b a {color:gray;} in master stylesheet and then someone develops a plugin with a gray background that goes on faq page, now they need to use !important or create another id attribute to give higher specificity.

    Also, consider the use of multiple classes in a single body element:

    <body class="faq two_column big_footer"> ...
    
    0 讨论(0)
  • 2021-01-01 12:02

    An id selector is more specific than a class selector, which usually makes it a better choice for your use case.

    0 讨论(0)
  • 2021-01-01 12:03

    ID needs to be unique per page (if you want valid markup), meaning only one instance of a particular ID should exist on a page.

    Classes, on the other hand, can be applied to numerous elements per page. Use classes for things that reuse the same styles and use IDs for more unique elements that require their own styling.

    Ideally, use classes whenever possible and limit the use of IDs.

    For more information on ID, see here, and more on classes, see here.

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