Saturday, January 18, 2025
HomeProgrammingHow to Use Two CSS Classes on One Element

How to Use Two CSS Classes on One Element

You can apply multiple CSS classes to a single HTML element by separating the class names with a space in the class attribute. Here’s how you can do it:

Syntax

In HTML, specify multiple classes in the class attribute like this:

<tag class="class1 class2">Content</tag>

Each class will apply its respective styles to the element. If there are conflicting styles, the class listed later in the CSS file will take precedence due to the cascading nature of CSS.

See also  How do I find out which process is listening on a TCP

Example

HTML Code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Multiple CSS Classes</title>
    <style>
        .red-text {
            color: red;
        }
        .bold-text {
            font-weight: bold;
        }
    </style>
</head>
<body>
    <p class="red-text bold-text">This text is red and bold.</p>
    <p class="red-text">This text is red but not bold.</p>
    <p class="bold-text">This text is bold but not red.</p>
</body>
</html>

Result

  1. The first paragraph will have both red text and bold font.
  2. The second paragraph will have only red text.
  3. The third paragraph will have only bold text.
See also  How can I create a list of primitive integers in Java?

Notes

  1. Order of Classes: The order of the classes in the class attribute does not matter; all specified styles will apply unless there are conflicting rules.
  2. Conflicting Styles: If two classes define conflicting styles, the specificity of the selectors will determine which style takes precedence. If both have equal specificity, the one defined later in the CSS file will take precedence.
  3. Combining Classes: You can define styles for a combination of classes by using a selector in your CSS:
    .red-text.bold-text {
        text-transform: uppercase;
    }
    

    This rule applies only when both .red-text and .bold-text are applied to the same element.

By using multiple classes, you can make your styles modular and reusable, simplifying your CSS code structure.

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x