Home > Software design >  select mulitple class in one parent the short way
select mulitple class in one parent the short way

Time:10-29

I have this sample situation

<div ></div>

in the css

.main-class {
    maring-top:1px
}

so sometimes in my div I add at run time some other class so it could be

<div ></div>

or

<div ></div>

or

<div ></div>

so in my css

.main-class.c{
    margin-top: 5px;
}
.main-class.a{
    margin-top: 5px;
}
.main-class.b{
  margin-top: 5px;
}

or simply

.main-class.c,
.main-class.a,
.main-class.b{
      margin-top: 5px;
    }

this is too long, is there any other ways to do this if .main-class has any other (a , b , c) so the margin will be 5px?

I tried this

.main-class:has(.a, .b, .c)
{
margin-top :5xp;
}

and this does not work

CodePudding user response:

Some notes to start with:

  • There is no CSS property called maring-top.
.main-class.c {
  margin-top: 5px;
}
.main-class.a {
  margin-top: 5px;
}
.main-class.b {
  margin-top: 5px;
}

can be simplified to

.main-class.c,
.main-class.a,
.main-class.b {
  margin-top: 5px;
}

and even further to

.main-class:is(.c, .a, .b) {
  margin-top: 5px;
}

CodePudding user response:

In addition to connexo's answer, Sass enables you to write your code like below :

.main-class {
    margin-top:1px;
    &.a, 
    &.b, 
    &.c{
        background-color:orange;
    }
}

<div >A</div>
<div >B</div>
<div >C</div>
<div >D</div>

(Codepen)

  • Related