<"/> <">

Home  >  Article  >  Web Front-end  >  How to apply CSS styles to different elements with the same class name in HTML?

How to apply CSS styles to different elements with the same class name in HTML?

WBOY
WBOYforward
2023-09-13 15:45:07941browse

How to apply CSS styles to different elements with the same class name in HTML?

HTML classes is a global attribute used by HTML tags to specify an inherently case-sensitive list of classes. These classes are then used by CSS to apply styles to specific tags with that class, and by Javascript to manipulate the behavior, interactivity, or styling of HTML elements.

Method 1; Use dot (.) selector

In this approach, we will simply use the dot (.) selector to select multiple elements with the same class name and apply the same set of styles to them using CSS.

Example

In this example, we will select the "p" tag and the "span" HTML tag using their classes and assign them a text color of "red" using CSS.

<!DOCTYPE html>
<html lang="en">
<head>
   <title>How to apply CSS style to the different elements having the same class name in HTML?</title>
   <style>
      .sample {
         color: red;
      }
   </style>
</head>
<body>
   <p class="sample">This is p tag content!</p>
   <span class="sample">This is span tag content!</span>
</body>
</html>

Method 2: Use the "p" tag and the "span" HTML tag

In this approach, we will use CSS to apply a set of different styles to elements with the same class name. To do this, we will use the HTML tag name followed by a dot (.) selector to select a specific element and give it the required CSS styling.

Example

In this example, we will select the "p" tag and the "span" HTML tag using their classes and give them different text colors using CSS.

<!DOCTYPE html>
<html lang="en">
<head>
   <title>How to apply CSS style to the different elements having the same class name in HTML?</title>
   <style>
      p.sample {
         color: red;
      }
      span.sample {
         color: green;
      }
   </style>
</head>
<body>
   <p class="sample">This is p tag content!</p>
   <span class="sample">This is span tag content!</span>
</body>
</html>

in conclusion

In this article, we saw how to select HTML elements from class names and how to apply the same and different CSS styles to them using two different methods. In the first method, we use the dot (.) selector to select multiple elements with the same class name and apply the same style to them. In the second method, we apply different CSS styles to elements with the same class name using the HTML tag name followed by a dot (.) selector.

The above is the detailed content of How to apply CSS styles to different elements with the same class name in HTML?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete