Dynamically I create a set of boxes with slightly different height and want to appear 2, 3 or 4 of them (depending on the screen size) at the same row. I tried the following
The problem is that all bootstrap columns try to float left.
From MDN on floats:
when an element is floated it is taken out of the normal flow of the document. It is shifted to the left or right until it touches the edge of its containing box or another floated element.
So when you have uneven heighted elements, the correct behavior is to stack them to the side.
Luckily, there are a lot of way to correct this to the anticipated behavior:
From MDN on Clear:
The clear CSS property specifies whether an element can be next to floating elements that precede it or must be moved down (cleared) below them
For this exact structure, you can apply clear
to every other row using the nth-child selector:
.col-xs-6:nth-child(odd) {
clear: both;
}
Note: The nth-child selector won't work in IE8
.col-xs-6:nth-child(odd) {
clear: left;
}
.col-xs-6 {
border: 1px solid grey;
}
Two
Lines
Two
Lines
Three
Lines
Jump
Two
Lines
Two
Lines
Two
Lines
.clearfix
The Bootstrap way to do this is to use the clearfix class which applies the following styles:
.clearfix:before,
.clearfix:after {
content: " ";
display: table;
}
.clearfix:after {
clear: both;
}
Note: You can use selectively target different screen sizes by combining this with the responsive utility classes (i.e.
.visible-*-*
,.hidden-*
)
.col-xs-6 {
border: 1px solid grey;
}
Two
Lines
Two
Lines
Three
Lines
Jump
Two
Lines
Two
Lines
Two
Lines
.row
You can also just wrap every pair of columns into a new row. This is the least reusable, but if every set of items forms a logical group, it does create semantic markup.
.col-xs-6 {
border: 1px solid grey;
}
Two
Lines
Two
Lines
Three
Lines
Jump
Two
Lines
Two
Lines
Two
Lines
Depending on your use case, you might just benefit from making everything the same height. This would work well if you had similar content in every column and wanted a consistent looking grid.
.col-xs-6 {
height: 7rem;
}
.col-xs-6 {
height: 7rem;
}
.col-xs-6 {
border: 1px solid grey;
}
Two
Lines
Two
Lines
Three
Lines
Jump
Two
Lines
Two
Lines
Two
Lines