Display a sequence of Divs in two lines

Asked

Viewed 471 times

4

Good evening, I have the following structure of Ivs: 1 | 2 | 3 | 4 | 5 | 6 What I need to do is that this structure looks like this:

1 | 3 | 5
2 | 4 | 6

A single detail, is that I need to do this only using CSS, without adding any more div in the structure. My code follows here:

http://codepen.io/anon/pen/YPmOma

2 answers

2


One solution is to fix the CSS like this:

.teste{
  width:100px;
  height:100px;
  background-color:red;
  float:left;
  margin-left:10px;
  position: absolute;
}
.teste:nth-child(even){
  margin-top: 120px;
}
.teste:nth-child(4), .teste:nth-child(3){
  left: 120px;
}
.teste:nth-child(6), .teste:nth-child(5){
  left: 230px;
}

Notice I changed your duplicate Ids to classes. I joined position: absolute to the class, and then I gave more or less rules to each element.

Example: http://codepen.io/anon/pen/yymRMJ

  • OK Sergio, it works very well this way that it showed, but what if these Divis are generated dynamically?

  • @Danielswater as well? must be the same... take a look here: https://jsfiddle.net/m1y8e18b/

  • So, is that actually I do not know the amount of Divs understood? Then I think I would not give p to apply Nth-Child

  • @Danielswater I think Nth-Child is great for this. If you give me an example where this idea doesn’t work it says, I can take a look again.

0

My solution, assuming you can set the display property of the parent element of these elements, is to use the display: flex, and set the order properties to define the order of the elements within this div. It is important to set a maximum width to make the elements descend to the next line, and flex-wrap: wrap serves to make the elements "break" to the next line when the limit of a div is found.

.container {
  display: flex;
  flex-wrap: wrap;
  max-width: 30px;
}

.els:nth-child(1) {
color: red;
order: 1
}

.els:nth-child(2) {
  order: 4
}

.els:nth-child(3) {
  order: 2
}

.els:nth-child(4) {
  order: 5
}

.els:nth-child(5) {
  order: 3
}

.els:nth-child(6) {
  order: 6
}
<div class="container">

<div class="els">1</div>
<div class="els">2</div>
<div class="els">3</div>
<div class="els">4</div>
<div class="els">5</div>
<div class="els">6</div>

</div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.