Daniel Daniel - 2 months ago 15
CSS Question

Using n inside 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).

Answer

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>

Comments