user2456977
user2456977

Reputation: 3964

CSS parent and child selector correct syntax

I've been seeing CSS like this lately:

1.

.header {
    position: relative;
    max-height: 1000px;
    z-index: 1;

    .sidebar{
        padding: 25px 25px;
    }

    .menu{

        border-radius:0;
        min-height: 30px;
        height:100px;

        i{
            color:#CCC !important;
            width:40px;
        }
    }
}

I guess header is the parent class and sidebar and menu are child classes of header.

Is this valid CSS syntax or good practice?

Usually I would expect CSS like this:

2.

.header { ... }
.header .sidebar { ... }
.header .menu { ... }

or even

3.

.header { ... }
.header > .sidebar { ... }
.header > .menu { ... }

What is the difference between these 3 cases?

Upvotes: 1

Views: 190

Answers (2)

Mihai T
Mihai T

Reputation: 17697

First structure is SCSS ( a css preprocessor ) . That's the difference between first and 2&3.

SCSS is a special type of file for SASS, a program written in Ruby that assembles CSS style sheets for a browser. SASS adds lots of additional functionality to CSS like variables, nesting and more which can make writing CSS easier and faster. SCSS files are processed by the server running a web app to output a traditional CSS that your browser can understand.

The difference between 2&3 is the use of > which means " direct child selector " . For example .header .sidebar will select all .sidebar that are inside .parent regardless if they are children or grandchildren etc.

 <parent>
   <child></child>
   <child>
      <grandchild></grandchild>
   </child>
 </parent>

So it will select child and grandchild and further down the tree.

Using > will only select the child not the grandchild

Upvotes: 1

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167212

The first one looks like it's SCSS or LESS (or some other CSS Pre-Processor) and not CSS, which render as the #2. To give you an idea of the difference between using > and not is:

.header .sidebar { ... }
.header .menu { ... }

Selects .sidebar and .menu anywhere inside .header.

<div class="header">
  <div class="sidebar"></div>
  <div class="menu"></div>
</div>

<div class="header">
  <div class="wrap">
    <div class="sidebar"></div>
    <div class="menu"></div>
  </div>
</div>

The code works for both the cases above. While, if you use:

.header > .sidebar { ... }
.header > .menu { ... }

The above code will not the second one that's wrapped inside .wrap. The second code is a direct descendant or a direct child selector.

Upvotes: 3

Related Questions