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

社会主义新天地 提交于 2019-12-11 06:03:35

问题


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


回答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>



回答2:


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;
    }
  }
}



回答3:


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.



来源:https://stackoverflow.com/questions/47895004/is-it-possible-to-determine-number-of-children-of-any-container-using-any-sass-f

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!