James Trotter James Trotter - 23 days ago 4
CSS Question

How can I make my inline divs "nestle" in to one another, even though they're different sizes?

I have an issue with the display of the new website I'm working on. Basically, all the content will be shown in 2 columns, and this will be reduced to 1 when viewing from a smaller screen.

When I've added content to these boxes, the first "column" on the second row is lower than the second element on the first "row", I would like it so that my next row down maintains its margin from the element directly above it, not the element that was last parsed.

Here's an example of my problem:



body{
background-color:lightgray;
}

.box{
box-sizing: border-box;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;

width:48%;
margin:1%;
padding:10px;

background-color:white;

display:inline-block;
float:left;
}

<!DOCTYPE html>
<html lang="en">
<head>

</head>
<body>
<div class="box">
<h1>Box 1</h1>
Test content 1
</div>
<div class="box">
<h1>Box 2</h1>
its a bit longer<br/>
than the last one<br/>
<br/>
its a lot longer<br/>
than the last one actually<br/>
</div>
<div class="box">
<h1>Box 3</h1>
its cold and lonely down here :(<br/>
I want to be with my waifu Box 1<br/>
</div>
</body>
</html>





Here's how I actually want it to look:
Actual way I want it

How can I change the styles to match this? Is it possible?

Answer

You could use :nth-child() selector to select all 2n elements and float to right.

* {
  box-sizing: border-box;
}
body {
  background-color: lightgray;
}
.box {
  width: 48%;
  margin: 1%;
  padding: 10px;
  background-color: white;
  float: left;
}
.box:nth-child(2n) {
  float: right;
}
<div class="box">
  <h1>Box 1</h1> Test content 1</div>
<div class="box">
  <h1>Box 2</h1> its a bit longer
  <br/>than the last one<br/>
  <br/>its a lot longer
  <br/>than the last one actually<br/>
</div>
<div class="box">
  <h1>Box 3</h1> its cold and lonely down here :(
  <br/>I want to be with my waifu Box 1<br/>
</div>
<div class="box">
  <h1>Box 4</h1> its cold and lonely down here :(
  <br/>I want to be with my waifu Box 1<br/>
</div>

Comments