CSS Nth child calculates top height based on N

I am trying to use CSS to calculate the top height to add every 5 + 1 elements.

The following code moves a series of elements with an absolute location to the appropriate places.

.screen [data-app]:nth-child(5n-4) { left:0%; } .screen [data-app]:nth-child(5n-3) { left:20%; } .screen [data-app]:nth-child(5n-2) { left:40%; } .screen [data-app]:nth-child(5n-1) { left:60%; } .screen [data-app]:nth-child(5n) { left:80%; } 

This creates the illusion of five columns with absolutely positioned elements. Now what I would like to do is the next line of five, which also added top:180px to them, and after the line top:360px , etc. Etc.

Is it possible to do this without having to write CSS code for the position of each individual element. Some way to apply the top attribute for each group of five based on the value n of the current item.

+5
source share
1 answer

You can use SASS or Flexbox to achieve the result you are looking for. In this case, SASS will create a more bloated CSS file than ideal, but it will use the rules that you set, and Flexbox will be more reliable and easy to use.

HTML

 <div class="screen"> <div data-app>asdf1</div> <div data-app>asdf2</div> <div data-app>asdf3</div> <div data-app>asdf4</div> <div data-app>asdf5</div> <div data-app>asdf6</div> <div data-app>asdf7</div> <div data-app>asdf8</div> <div data-app>asdf9</div> <div data-app>asdf10</div> <div data-app>asdf11</div> </div> 

Sass

 .screen { position: relative; } .screen [data-app] { $height: 180px; $offset: 20%; $blocks_per_row: 5; position: absolute; width: 20%; @for $i from 0 through 20 { $y: floor($i / $blocks_per_row); $x: $i % 5; &:nth-child(#{$y}n+#{$i}) { left: $x * $offset; top: $y * $height; } } } 

Flexbox

 .screen { display: flex; flex-flow: row wrap; justify-content: flex-start; align-content: flex-start; align-items: flex-start; } .screen [data-app] { flex: 0 1 20%; height: 180px; } 

As you can see, there is no upper limit to the Flexbox solution, and it is very clean. I hope any of these solutions help you.

+1
source

Source: https://habr.com/ru/post/1212864/


All Articles