Tell me about ID and class in CSS?

ID and Class in CSS:

📌 Need for it:

  1. Style Different Elements: IDs and classes in CSS are needed to apply styles to specific HTML elements or groups of elements, allowing developers to customize the appearance and layout of web pages according to their design requirements.

🔍 What is it:

  1. ID: An ID is a unique identifier assigned to a single HTML element. It is defined using the id attribute in HTML and preceded by a hash symbol (#) in CSS selectors.
  2. Class: A class is a reusable identifier assigned to one or more HTML elements. It is defined using the class attribute in HTML and preceded by a dot (.) in CSS selectors.

❓ How is it used in the real world:

  1. Styling Individual Elements: IDs are often used to style individual elements that require unique styling, such as headers, footers, or main content sections of a web page.
  2. Styling Multiple Elements: Classes are commonly used to style multiple elements that share similar characteristics or belong to the same category, such as navigation menus, buttons, or cards.

Code snippet:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>ID and Class Example</title>
  <style>
    /* Styling an element with ID */
    #header {
      background-color: #007bff;
      color: #fff;
      padding: 10px;
      text-align: center;
    }

/ Styling elements with Class /
.button {
display: inline-block;
padding: 10px 20px;
background-color: #28a745;
color: #fff;
text-decoration: none;
border-radius: 5px;
}

.button:hover {
background-color: #218838;
}


</style>  

</head>

<body>

<!-- HTML Element with ID –>

<div id="header">

<h1>Welcome to My Website</h1>

</div>

<!-- HTML Elements with Class –>

<div>

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed ut magna nec lorem tincidunt elementum.</p>

<!-- Button with Class –>

<a href="#" class="button">Learn More</a>

</div>

</body>

</html>

In this example:

  • The <div> element with the ID header is styled with a specific background color, text color, padding, and text alignment.
  • The elements with the class button are styled as buttons with specific padding, background color, text color, text decoration, and border radius. Additionally, a hover effect is applied to the button when the mouse cursor is over it.