Amit Panasara
Amit Panasara

Reputation: 680

After-Before pseudo in CSS3 for multiple classes

How to assign after & before pseudo classes to multiple CSS-classes

For example:

[class*="divclass-"]::before, ::after{
      border-radius: 50%;
      width: 30%;
      height : 30%;
      border: 3px solid red;
}

Upvotes: 1

Views: 1796

Answers (2)

Gibin Ealias
Gibin Ealias

Reputation: 2859

Consider this HTML structure, where you have a <div> which have children <span> and <p>. And another <span> and <p> as siblings.

<div>
  <span>abc</span>
  <p>xyz</p>
</div>
<span>123</span>
<p>456</p>

For example, if we need to change the colour of the children, we could write on your way,

div span, p{
  color: red;
}

This problem with this is that, it will change the colour of the sibling <p>456</p> too as the style is applied globally to all the paragraph tags.

And the solution is to follow specificity as we did with the <span> and write the selectors as

div span, 
div p{
  color: red;
}

The same rule applies to pseudo-elements as well. Hence the solution is,

[class*="divclass-"]::before, 
[class*="divclass-"]::after{
  border-radius: 50%;
  width: 30%;
  height : 30%;
  border: 3px solid red;
}

Note 1

If you are working on SASS, your syntax could be,

[class*="divclass-"]{
  &::before, 
  &::after{
    border-radius: 50%;
    width: 30%;
    height : 30%;
    border: 3px solid red;
  }
}

Note 2

The before and after pesudo-elements require the content property.

Hope this helps.

Upvotes: 1

Alex83690
Alex83690

Reputation: 817

The comma does not mean that the following elements are children of the same selector (here [class*="divclass-"]). It just allows you to chain the selectors.

@see https://www.thoughtco.com/comma-in-css-selectors-3467052

Here is the solution:

[class*="divclass-"]::before, 
[class*="divclass-"]::after {
      border-radius: 50%;
      width: 30%;
      height : 30%;
      border: 3px solid red;
      content: '';
}
<div class="divclass-1" style="height: 10px; width: 10px"></div>

Upvotes: 1

Related Questions