Regnalf
Regnalf

Reputation: 124

CSS selector with deep level

in the following html/css code i want to select all elements "row" only on level 1 and not deeper. But the child selector also selects the nested "row" elements to? How can i select only level 1 "row" elements?

.content > .row
{
  background-color: green;
}
<div class="content">
  <div class="row">Level 1 - Row 1</div>
  <div class="row">Level 1 - Row 2
    <div class="row">Level 2 - Row 1</div>
    <div class="row">Level 2 - Row 2</div>
  </div>
  <div class="row">Level 1 - Row 3</div>
</div>

Upvotes: 2

Views: 4059

Answers (2)

Anurag Srivastava
Anurag Srivastava

Reputation: 14413

The selector is working correctly, the green background is applied to only the parent row but the children row elements display it too. You can easily override that.

.content > .row {
  background-color: green;
}
.content > .row .row { background-color: red; }
<div class="content">
  <div class="row">Level 1 - Row 1</div>
  <div class="row">Level 1 - Row 2
    <div class="row">Level 2 - Row 1</div>
    <div class="row">Level 2 - Row 2</div>
  </div>
  <div class="row">Level 1 - Row 3</div>
</div>

Upvotes: 2

nishit chittora
nishit chittora

Reputation: 1034

That's the expected behavior. Because it inherits background-color from parent element. But you can change the child element background-color

.content > .row
{
  background-color: green;
}
.content > .row > .row{
  background-color: white
 }
<div class="content">
  <div class="row">Level 1 - Row 1</div>
  <div class="row">Level 1 - Row 2
    <div class="row">Level 2 - Row 1</div>
    <div class="row">Level 2 - Row 2</div>
  </div>
  <div class="row">Level 1 - Row 3</div>
</div>

Upvotes: 2

Related Questions