Wednesday, January 20, 2016

CSS: Selectors with spaces different from Selectors w/out spaces

CSS Selectors with Spaces between

Recently, I was following a YouTube in learning more about jQuery and came across the author's CSS.

He had the following:

.tab-panels .panel.active {
  display: block;
}

I had almost exact code, but wanted to add a space in between ".panel" and ".active" for easier reading.

.tab-panels .panel .active {
  display: block;
}

Here's the HTML we had (or that he had and I copied):
      <div class="tab-panels">
        <ul class="tabs">
          <li class="active">panel1</li>
          <li>panel2</li>
          <li>panel3</li>
          <li>panel4</li>
        </ul>
      </div>

However, my active panel didn't display. When I typed exactly the code that the author had, then my active panel displayed. Why?

Well, learning from http://stackoverflow.com/questions/6885013/how-to-select-classes-with-spaces, adding spaces in between CSS selectors creates new meaning for the class attribute. The CSS rendering is looking for elements with class="active" that have a parent element with class="panel". In detail, this will also look for the next parent element (or grandparent element) with class="tab-panels". By removing the space in between the selectors, we'll now look for the element with class="panel active" (where the dot is replaced with a space in class attribute value).

No comments:

Post a Comment