Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
307 views
in Technique[技术] by (71.8m points)

Making nth child a random variable in CSS

I want to assign a random value to n in the css. Ideally without javascript (and there are suggestion on how to do this in various posts but I then don't know how to insert the javascript into the css as the nth child element only seems to accept 'odd', 'even' 'n' or a numerical value.

Code as it stands:

.gallery > .gallery__list > li:nth-child(4n) {
grid-column: span 3; /* Spans two columns */
grid-row: span 3; /* Spans two rows */
}

I simply want '4' to a random value between 1 and 5 so it could be 2n sometimes and 3n others.

question from:https://stackoverflow.com/questions/65836580/making-nth-child-a-random-variable-in-css

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This is not possible with CSS - it's a styling language, not a programming language and doesn't have the capacity to 'run' any code. However, it is relatively straightforward with JS. I originally misread the selector as just 4, not 4n, which makes things a little more involved:

const listItems = document.querySelectorAll('.gallery > .gallery_list > li');
const separator = Math.ceil(Math.random() * 4);

listItems.forEach((item, i) => {
  if ((i + 1) % separator === 0) {
    item.classList.add('span-3');
  }
});
.span-3 {
  grid-column: span 3;
  grid-row: span 3;
  color: red;
}
<div class="gallery">
  <ul class="gallery_list">
    <li>Item One</li>
    <li>Item Two</li>
    <li>Item Three</li>
    <li>Item Four</li>
    <li>Item Five</li>
    <li>Item Six</li>
    <li>Item Seven</li>
    <li>Item Eight</li>
    <li>Item Nine</li>
    <li>Item Ten</li>
  </ul>
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...