Asguard
Asguard

Reputation: 101

How to nest multiple css attributes inside another attribute

I am getting an html file as a string and I need to change the styling that are coming in to prevent it from changing the parent styling.

Instead of going through each style and changing it from

    .inner-div{height: 50px;}

to

    .outter-div .inner-div{height: 50px;}

on each element, I would like to do something like

    .outter-div {
        .inner-div{height: 50px;}
        .inner-div2{height: 50px;}
    }

however that does not work

Is there a way to have multiple attributes nested inside of another attribute, instead of having to add the parent on each attribute?

Upvotes: 0

Views: 249

Answers (2)

Danield
Danield

Reputation: 125463

Assuming the inner class names all start the same (with 'inner'), then this can be done with an attribute selector. like this:

.outer-div [class^=inner] {
  height: 50px; 
}

Demo

If this is not the case, then...use a CSS preprocessor like others have mentioned.

PS: just for the record...

CSS selectors level 4 has added the :matches pseudo-class in order to group selectors more easily.

The syntax looks like this: :matches( selector[, selector]* )

In your case, it would be:

.outer-div :-matches(.inner-div, .inner-div2 ) {
        height: 50px;
}

You can read more about it this CSS-tricks post

NB: Currently there is no browser support for :matches, however the :matches pseudo class was once called :any in the spec, supported with -moz- and -webkit- prefixes. See MDN on :any

Here's a working example for webkit using :any:

Codepen

Upvotes: 0

Sarhanis
Sarhanis

Reputation: 1587

To do something like that, you'd have to use a CSS pre-processor.

Two popular candidates are Less and Sass.

Less and Sass extend CSS to provide extra features, including the ability to nest multiple attributes. This Less or Sass code is then fed into a pre-processor, which transforms it into standard CSS that a browser understands and can be deployed as part of your website or app.

Upvotes: 2

Related Questions