Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using n inside calc

Tags:

css

css-calc

can I use the n variable inside a calc expression?

For example:

.child:nth-child(n) {
   margin-left: calc(n * 46px);
}

My Code:

<div class="share-buttons">
  <div class="share-button-main"></div>
  <div class="share-button share-facebook">
    <img src="facebook.png" alt="" />
  </div>
  <div class="share-button share-whatsapp">
    <img src="whatsapp.png" alt="" />
  </div>
  <div class="share-button share-email">
    <img src="email.png" alt="" />
  </div>
  <div class="share-button share-sms">
    <img src="sms.png" alt="" />
  </div>
</div>

CSS (Sass):

.share-buttons {
  position: relative;
    display: flex;

  .share-button-main {
    width: 46px;
    height: 46px;
    z-index: 2;
    cursor: pointer;
    content: url('share-menu-share-closed.png')
  }

  .share-button {
    position: absolute;
    top: 0;
    left: 0;
    width: 46px;
    height: 46px;
    z-index: 1;
    transition: all .3s ease;
    opacity: 0;
  }

  &.open {
    .share-button-main {
      content: url('share-menu-share-opened.png')
    }
    .share-button {
      opacity: 1;
    }

    .share-facebook {
      left: 56px;
    }

    .share-whatsapp {
      left: 112px;
    }

    .share-email {
      left: 168px;
    }

    .share-sms {
      left: 224px;
    }
  }

    img {
        width: 46px;
        height: 46px;
    }
}

Javascript (JQuery):

$('.share-button-main').click(function() {
  $('.share-buttons').toggleClass('open');
});

I'm basically trying to acheive a dynamic opening effect to the menu so if I add or remove elements it'll still work (and not like now when I set each div's left separately).

like image 438
Naxon Avatar asked Jul 27 '16 15:07

Naxon


3 Answers

Not exactly what you may be after, but you can achieve a similar effect with scss if you know the number of elements. Just bear in mind that this will generate a lot of css:

@for $i from 1 through 7 {
    &:nth-child(#{$i}) {
      margin-left: calc(#{$i} * 46px);
    }
  }
like image 96
David Avatar answered Nov 11 '22 16:11

David


You can't, as mentioned by @SLaks. But this can be solved by placing each next element inside the previous one.

See with divs:

div {
  margin-left: 46px
}
<div>test
  <div>test
    <div>test
      <div>test</div>
    </div>
  </div>
</div>

Or, use jQuery.

var margin=0;
$("div").each(function(){
  $(this).css("margin-left",margin+=46)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>text</div>
<div>text</div>
<div>text</div>
<div>text</div>
<div>text</div>
like image 39
nicael Avatar answered Nov 11 '22 16:11

nicael


No; you can't do that.

The counter feature can almost do that, except that it can't be used with calc() either.

like image 39
SLaks Avatar answered Nov 11 '22 15:11

SLaks