Search code examples
sassmixinsscss-lint

Is it possible to determine number of children of any container using any SASS function?


Is it possible to determine number of children of any container using any SASS function?

For example, I have a container which has 3 columns:

    <div class="columns columns_3">
        <div class="column"></div>
        <div class="column"></div>
        <div class="column"></div>
    </div>

For this container, I want to implement a mixin which is +columns_3 But if the container has nth number of children, mixin will be +columns_n


Solution

  • What you want is to know how many childs haves an element and set the right class to it. You need Javascript to detect the number of childs, HTML and CSS.

    SCSS

    .element {
      $width: 100%;
      width: $width;
    
      div {
        height: 100px;
        float: left;
        border:1px solid #000;
        box-sizing: border-box;
      }
    
      @for $i from 1 through 12 {
        &--#{$i} div {
          width: $width/$i;
        }
      }
    }
    

    var element = document.getElementsByClassName('element')[0];
    var childs = element.childElementCount;
    element.classList.add("element--"+childs);
    .element {
      width: 100%;
    }
    .element div {
      height: 100px;
      float: left;
      border: 1px solid #000;
      -webkit-box-sizing: border-box;
              box-sizing: border-box;
    }
    
    .element--4 div {
      width: 25%;
    }
    <div class="element">
      <!-- childs -->
      <div></div>
      <div></div>
      <div></div>
      <div></div>
    </div>