Home >Web Front-end >CSS Tutorial >How Can I Style Multiple Divs with Similar Class Names Using CSS Selectors?

How Can I Style Multiple Divs with Similar Class Names Using CSS Selectors?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-27 07:57:11484browse

How Can I Style Multiple Divs with Similar Class Names Using CSS Selectors?

Utilizing Wildcards in CSS Classes

In your query, you aim to style multiple divs with the common class "tocolor" while including unique identifiers (e.g., tocolor-1, tocolor-2). You attempted to simplify this using the wildcard "*" in CSS, but it proved unsuccessful.

To achieve your desired result, we introduce attribute selectors in CSS. Attribute selectors allow you to target elements based on specific attributes, such as their class value.

For your scenario, you can utilize the following CSS selector:

div[class^="tocolor-"], div[class*=" tocolor-"] {
  color: red;
}

Here's how it works:

  • [class^="tocolor-"]: This selector matches elements whose class attribute starts with "tocolor-".
  • [class*=" tocolor-"]: This selector matches elements whose class attribute contains "tocolor-" anywhere within the string, preceded by a space character.

By combining these two selectors, you can target any element with a class that fulfills either of these criteria.

For instance, given the following HTML structure:

<div class="tocolor tocolor-1">tocolor 1</div>
<div class="tocolor tocolor-2">tocolor 2</div>
<div class="tocolor tocolor-3">tocolor 3</div>

Applying the CSS selector above will set the color of all these divs to red.

Check out this interactive demo on JSFiddle: http://jsfiddle.net/K3693/1/

For more comprehensive information on CSS attribute selectors, refer to the following resources:

  • CSS Attribute Selectors (W3Schools): https://www.w3schools.com/cssref/css_selectors.asp
  • Attribute Selectors (MDN Web Docs): https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors

The above is the detailed content of How Can I Style Multiple Divs with Similar Class Names Using CSS Selectors?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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