Home > Enterprise >  How to select several children of an element in CSS
How to select several children of an element in CSS

Time:09-21

I have an element with id. I try to choose some of its children via CSS selectors.
#myDiv span, #myDiv i works but I wonder if there is a shorter way for this.

I've tried nested selectors like

#myDiv {
  & span, i {
    color: red
  }
}

but didn't work.

#myDiv span, #myDiv i {
  color: red
}
<div id="myDiv">
  <span>My Span</span>
  <p>My P</p>
  <i>My I</i>
</div>

CodePudding user response:

Your nested code is in SCSS not in CSS, and there is no nesting in CSS.

The shortest CSS code if you will not add any another elements under this container in future will be

#myDiv *:not(p) {
   color: red
}

CodePudding user response:

If you want it to be recursive (let's say, in the future, some #myDiv elements will have their own child elements), use:

#myDiv > *:not(p) {
   color: red
}

CodePudding user response:

You can like this:

#myDiv {
  & span, & i {
    color: red
  }
}

it seems that you forgot to put "&" before every new class selector.

  •  Tags:  
  • css
  • Related