Difference between id and class in CSS and when to

2018-12-31 08:28发布

This question already has an answer here:

<style>
    #main{
        background: #000;
        border: 1px solid #AAAAAA;
        padding: 10px;
        color: #fff;
        width: 100px;
    }
</style>

<div id="main">
    Welcome
</div>

Here I gave an id to the div element and it's applying the relevant CSS for it.

OR

<style>
    .main{
        background: #000;
        border: 1px solid #AAAAAA;
        padding: 10px;
        color: #fff;
        width: 100px;
    }
</style>
<div class="main">
    Welcome
</div>

Now here I gave a class to the div and it's also doing the same job for me.

Then what is the exact difference between id and class and when should I use id and when should I use class. I am a newbie in CSS and Web design and a little confused while dealing with this.

标签: html css
15条回答
闭嘴吧你
2楼-- · 2018-12-31 09:07

id selector can be used to more elements. here is the example:

css:

#t_color{
    color: red;
}
#f_style{
    font-family: arial;
    font-size: 20px;
}

html:

<p id="t_color"> test only </p>
<div id="t_color">the box text</div>

I tested on internet explorer (ver. 11.0) and Chrome (ver.47.0). it works on both of them.

The "unique" only means one element can not have more than one id attributes like class selector. Neither

<p id="t_color f_style">...</p>

nor

<p id="t_color" id="f_style">...</p>
查看更多
长期被迫恋爱
3楼-- · 2018-12-31 09:08

As pretty much everyone else has said use ID for one-off elements and class for multiple use elements.

Here is a quick, over simplified example, take HTML and HEAD tags as read

<body>
    <div id="leftCol">
        You will only have one left column
    </div>
    <div id="mainContent">
        Only one main content container, but.....
        <p class="prettyPara">You might want more than one pretty paragraph</p>
        <p>This one is boring and unstyled</p>
        <p class="prettyPara">See I told you, you might need another!</p>
    </div>
    <div class="footer">
        Not very HTML5 but you'll likely only have one of these too.
    </div>
</body>

Also, as mentioned in other answers ID are well exposed to javascript, classes less so. However modern javascript frameworks like jQuery leverage class for javascript too

查看更多
伤终究还是伤i
4楼-- · 2018-12-31 09:09

IDs must be unique--you can't have more than one element with the same ID in an html document. Classes can be used for multiple elements. In this case, you would want to use an ID for "main" because it's (presumably) unique--it's the "main" div that serves as a container for your other content and there will only be one.

If you have a bunch of menu buttons or some other element for which you want the styling repeated, you would assign them all to the same class and then style that class.

查看更多
登录 后发表回答