darKnight
darKnight

Reputation: 6481

Arrange items of different heights in a grid

So I have various UI components of varying dimensions, which I am putting up together in a page. I want to arrange them horizontally in a grid, where each row should be equal to the height of the component which has the maximum height in that row. There are no fixed number of columns for each row. Components should be placed next to each other without their dimensions being changed, and should automatically wrap to the next row if there is no space left for that component in that row.

I tried using bootstrap, but I must specify column width for each component like col-xs-number, which I can't do as I can't freeze the number of items in a row.

Edit: The application uses bootstrap version 3, so can't use V4.

Is this possible?

Upvotes: 0

Views: 458

Answers (2)

Peter B
Peter B

Reputation: 24147

You can do it without any kind of Bootstrap, just using display: inline-block for the elements.

Below is a demo where I add 12 elements of varying heights in a container div, where the width of the container div is set to a random value every time it is run to show how it will wrap differently each time.

var heights = [100, 20, 80, 140, 65, 90, 30, 70, 130, 55, 75, 100];
for (var i = 0; i < heights.length; i++) {
  $('#x').append($('<div style="height:' + heights[i] + 'px"></div>'))
}
var w = Math.floor((Math.random() * 400) + 100);
$('#x').css("width", w + "px");
#x div {
  display: inline-block;
  vertical-align: text-top;
  width: 50px;
  background: green;
  margin: 10px;
}

#x {
  border: solid 1px #888
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<hr>
<div id="x"></div>
<hr>

Upvotes: 1

Radosvet Petrov
Radosvet Petrov

Reputation: 748

Check flexbox, bootstrap 4 is using flexbox, so you can have columns without numbers.

Example:

.container{
  border:1px solid black;
}

.col:first-of-type{
  background:white;
}


.col:nth-of-type(2){
  background:green;
}

.col:last-of-type{
  background:red;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<div class='container'>
  <div class="row">
    <div class="col">First</div>
    <div class="col">Second</div>
    <div class="col">Third</div>
  </div>
</div>

Upvotes: 0

Related Questions