1

I want to do something like CSS:

.parent {
  height: 100px;
  width: 100px;
  background-color: black;

  .child {
    height: 50px;
    width: 50px;
    background-color: red;
  }
}

HTML:

<div class="parent">
  <div class="child">
  </div>
</div>

But this doesn't work. I will have to do this:

.parent {
  height: 100px;
  width: 100px;
  background-color: black;
}

.parent .child {
  height: 50px;
  width: 50px;
  background-color: red;
}

I will have to type the parent name again and again if there are many children elements inside parent. Is there any short way to do it?

noob_coder
  • 35
  • 2
  • 7
  • mate you can just make it outide parent ...like you set the parent you set the child: .parent { height: 100px; width: 100px; background-color: black; } .child { height: 50px; width: 50px; background-color: red; } – NoobDEV-GBL Aug 03 '21 at 11:44
  • Try `scss`, which supports the nesting and other multiple features – Abin Thaha Aug 03 '21 at 12:02
  • We might get this in a future version of CSS - https://drafts.csswg.org/css-nesting/ – CBroe Aug 03 '21 at 12:04
  • @NoobDEV-GBL I want to apply the css properties to only .child inside .parent. If I keep it outside, it will be applied to all classes with class name "child" which I don't want – noob_coder Aug 03 '21 at 12:05
  • @noob_coder yes i know, thats why i remove my answer – NoobDEV-GBL Aug 03 '21 at 12:07

2 Answers2

1

What you're trying to do with css (nesting related styles) requires a pre-processor. I would recommend reading about Sass.

If you're trying to be really specific, and apply these properties only to elements inside .parent that have the .child class, you need to have the parent selector before the actual selector. ( .parent .child { })

If you want to apply it to all elements that have a class .child you could just directly apply the style, without specifying a parent selector.

.child {
  height: 50px;
  width: 50px;
  background-color: red;
}

.parent {
  height: 100px;
  width: 100px;
  background-color: black;
}
<div class="parent">
  <div class="child">
  </div>
</div>
Omar Siddiqui
  • 1,625
  • 5
  • 18
0

Using SCSS, you can have the multi level nesting.

On top of that feature, there are other beautiful features that's being provided by SCSS-lang. Check out the official site

Abin Thaha
  • 4,493
  • 3
  • 13
  • 41