Matt Hintzke
Matt Hintzke

Reputation: 8004

CSS selector issue for multiple elements

I thought I had my CSS down fairly well but I cannot seem to figure out why this problem occurs. I must be doing something wrong.

So if I want to select multiple elements that are children to a div I could write:

#mydiv > input, label{

}

Am I correct? I thought this to be true until I realized that other inputs and labels in my site were inheriting these CSS properties even though they were not in the div called #mydiv. To fix the issue I had to use:

#mydiv > input, #mydiv > label {

}

But I am pretty sure that this is not the quickest way to do so. I tried checking the Selector Page on W3.org but they do not give an example for my situation.

What am I doing wrong?

Upvotes: 2

Views: 334

Answers (3)

Matt Ball
Matt Ball

Reputation: 359966

Am I correct?

No. The grouping selector (comma) has the lowest precedence, so you cannot use it to select multiple elements that are children of a div using this selector:

#mydiv > input, label

The most concise selector is the one that you found on your own:

#mydiv > input, #mydiv > label

You can DRY things up a bit using nested rules in LESS or Sass, though that does introduce a dependency in your code and/or build process.

Upvotes: 4

Cameron Christensen
Cameron Christensen

Reputation: 460

Your second method is good

#mydiv > input, #mydiv > label {

}

If you wanted to somehow do this without using multiple selectors separated by a comma, you could use a class name for both your input and label elements

.your-class-name {

}

or if for some reason input and label were the only two types of child elements for #mydiv, then you could use the universal selector like this:

#mydiv > * {

}

Upvotes: 1

Chris Laplante
Chris Laplante

Reputation: 29658

Your second snippet is the simplest way to do it with pure CSS. The comma , separates isolated CSS selectors, so that's why you needed to begin each with #mydiv for both selectors.

You could use something like LESS, which would allow nested rules. Non-germane example:

#header {
  h1 {
    font-size: 26px;
    font-weight: bold;
  }
  p { font-size: 12px;
    a { text-decoration: none;
      &:hover { border-width: 1px }
    }
  }
}

But you're probably better off with pure CSS.

Upvotes: 1

Related Questions