Tuesday, 29 October 2024

Introduction To CSS Class Selectors: A Step-by-Step Guide with Practical Examples

A class selector in CSS is used to apply styles to HTML elements that have a specific class attribute. Class selectors are versatile because they allow you to apply the same styles to multiple elements, regardless of their type, making them ideal for consistent styling across your web pages.

Syntax

.class-name {
    property: value;
}

1.   .class-name: The period (.) indicates that you are selecting a class. Replace class-name with the name of your class.

2.   property: value;: This is where you define the CSS properties you want to apply.

 

Example Using External CSS File

Let's create an example where we apply styles using a class selector.

 

class-selector.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Class Selector Example</title>
    <link rel="stylesheet" href="../../css/selectors/class-selector.css">
</head>
<body>
    <h1 class="highlight">Welcome to My Website</h1>
    <p class="highlight">This is a paragraph styled using a class selector.</p>
    <p>This paragraph does not have the class and will not be styled.</p>
</body>
</html>

class-selector.css

/* CSS file: styles.css */
.highlight {
    color: white;
    background-color: green;
    padding: 10px;
    border-radius: 5px;
}

Open ‘class-selector.html’ file in the browser, you can see below kind of screen.



Explanation

1.   HTML File: In the class-selector.html file, two elements (h1 and p) have been assigned the class highlight.

2.   CSS File: In the class-selector.css file, the .highlight class is defined with the following styles:

a.   color: white;: Sets the text color to white.

b.   background-color: green;: Sets the background color to blue.

c.    padding: 10px;: Adds padding inside the elements.

d.   border-radius: 5px;: Rounds the corners of the elements.

 

When to Use Class Selectors

1.   Reusability: Use class selectors when you want to apply the same styles to multiple elements on the page.

2.   Consistency: They ensure a consistent look and feel across your website.

3.   Specificity: Classes are more specific than element selectors but less specific than ID selectors. They are a good middle ground for styling.

4.   Modularity: Class selectors allow you to create modular styles that can be reused in different parts of your site without redundancy.

 

This approach helps to maintain cleaner and more organized code, making it easier to update and manage your styles.

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment