When to use class and id in css

青灯夜游
Release: 2023-01-04 09:38:55
Original
3272 people have browsed it

When the css style is applied to more than one element, use class to define it; when the css style applies to only one element, use id to define it. Reason: ID cannot be repeated and can only be used once. One ID can only be used for one label element; class can be used repeatedly, and the same class can be defined on multiple label elements.

When to use class and id in css

The operating environment of this tutorial: windows7 system, css3 version, Dell G3 computer.

Tutorial recommendation: css video tutorial

In addition to the selectors in CSS, you can select HTML predefined tags, such as ,

, < ;div>. You can also choose a user-defined id or class. The main difference between id and class is that id cannot be repeated and can only be used once. One id can only be used for one label. Classes can be reused, and the same class can be defined on multiple tags. In fact, the difference between id and class can be seen from the name. id is the identifier, and class is the class.

So when to use id and when to use class?

  • When a css style is used for more than one element, use class to define it.

  • When the css style is applied to only one element, use id to define it.

For example, a navigation bar. If there is only one top navigation bar in each page, you can use the id to define it.

<nav id="nav"></nav>
// 或者
<div id="nav"></div>
Copy after login

For example, a product list has the same style. You can use class to define

<ul id="list">
    <li class="list-item">1</li>
    <li class="list-item">2</li>
    <li class="list-item">3</li>
</ul>
Copy after login

For more programming-related knowledge, please visit: Programming Teaching! !

The above is the detailed content of When to use class and id in css. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template