0

I have a series of elements in different React components to which I want to modify "dynamically" the padding. Let's imagine that I have the following:

<div className="blue-content">
<div className="menu-black">
<div className="big-content">
<div className="red-content">

*I do not always know the complete className

how could I via CSS or Javascript change the style of all the ones ending with "content"?

Fuzz
  • 39
  • 4
  • Easily: `[class$="-content"]` { ... } with the [w3schools: CSS attribute$=value Selector](https://www.w3schools.com/cssref/sel_attr_end.asp) – Rene van der Lende Aug 16 '22 at 13:52
  • Check out the MDN for attribute selectors: https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors – disinfor Aug 16 '22 at 13:53

2 Answers2

1

CSS Way:

Just add the used attribute name at the beginning which follows [class$='-content']

Like this example below, where i am using a div as a selector:

div[class$='-content']{
  color:red;
}
<div class="red-content"> test </div>
<div class="x-content"> test1 </div>
<div class="y-content"> test2 </div>
<div class="z-content"> test3 </div>

Further Explaination:

You could use $= to select className end with specific string.

or

Use *= to match any className contain this string.

Like here (*= example):

div[class*='-content']{
  color: green;
}
<div class="red-content"> test </div>
<div class="x-content-abc"> test1 </div>
DnD2k21
  • 221
  • 1
  • 6
  • 25
1

You can use attribute selector. $= may be use to match the end of the attribute. Try:

div[class$='-content'] {
  background-color: skyblue;
}

div {
  padding: 10px;
  border: 1px solid black;
}
<div class="blue-content"></div>
<div class="menu-black"></div>
<div class="big-content"></div>
<div class="red-content"></div>

Just in case you need to match the start of the attribute, you may use attribute^=start

Irfanullah Jan
  • 3,336
  • 4
  • 24
  • 34