2

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

Touhid Rahman
  • 119
  • 11
  • Not that I'm aware of, however if you explain your problem and what you need to achieve, it's likely that others have been there before and have an answer, maybe not knowing the number is not actually the problem. – OK sure Dec 19 '17 at 20:57
  • Do you have a range? or is it 1-9999999? – OK sure Dec 19 '17 at 21:05
  • Its better if there is no range, so I can implement in any case. But 1-12 range should solve my problem for now :) – Touhid Rahman Dec 19 '17 at 21:24
  • SASS can't read your HTML, if that's what you're asking. – René Dec 19 '17 at 21:32

3 Answers3

1

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>
llobet
  • 2,672
  • 23
  • 36
0

Well if you have a range, you could potentially use a for loop - depending what you need to do. For example:

$gridWidth = 100%;
@for $numItems from 1 through 12 {
  .columns_#{$numItems} {
    .column {
      width: $gridWidth / $numItems;
    }
  }
}
OK sure
  • 2,617
  • 16
  • 29
-2

I think you can make this :

@function number(val) { @return val };


@mixins +columns_#{number(10)} {

  // Your code;

}

I'm not sure I understand what you explain.

KolaCaine
  • 2,037
  • 5
  • 19
  • 31
  • How will it determine the number of children within .columns container? – Touhid Rahman Dec 19 '17 at 21:26
  • Isn't JavaScript.. If you want to determinate dynamically number of an element please use a JavaScript solution. But with in my case, if you set a 3 and you use that mixins, in your HTML you need to have three children. – KolaCaine Dec 19 '17 at 21:30