Creating a responsive layout with Bootstrap using fluid rows and columns of varying heights

Using dynamic creation, I am tasked with generating a set of boxes each with slightly varying heights and ensuring that 2, 3, or 4 of them (based on screen size) appear on the same row. Here is an example of my attempt using Bootstrap:

<div class="container-fluid">
  <div class="row-fluid">
    <div class="col-xs-6">
      Two<br>Lines
    </div>
    <div class="col-xs-6">
      Two<br>Lines
    </div>
    <div class="col-xs-6" style="background-color: red">
      Three<br>Lines<br>Jup
    </div>
    <div class="col-xs-6">
      Two<br>Lines
    </div>
    <div class="col-xs-6">
      Two<br>Lines
    </div>
    <div class="col-xs-6">
      Two<br>Lines
    </div>
  </div>
</div>

The issue I'm facing is the space below the third column.

 A  B
 C  D
 C  E <- Should wrap to next row, because of C
 F  G

Any insights on how to resolve this? I've heard suggestions about using clearfix, but I am concerned it might lead to issues and messy code when dealing with a different number of columns.

I appreciate your help!

Answer №1

The Dilemma

There exists a fundamental issue with the default left floating behavior of bootstrap columns.

Per MDN's documentation on floats:

Once an element is floated, it no longer adheres to the regular document flow. Instead, it shifts either to the left or right border until it encounters its containing box or another floated element.

Hence, when confronted with elements of varying heights, the anticipated outcome would involve aligning them next to each other.

Fortunately, multiple solutions are available to correct this discrepancy and attain the intended layout:


Employing CSS Clear Property

As outlined in MDN's detailed explanation of Clear:

The clear CSS property dictates whether an element can be positioned adjacent to preceding floated elements or should shift below them (clearing).

To specifically tackle this structural concern, you can utilize the clear property for every alternate row by leveraging the nth-child selector:

.col-xs-6:nth-child(odd) {
    clear: both;
}

Note: The nth-child selector lacks IE8 support

Check out the Demo on jsFiddle / Stack Snippets:

.col-xs-6:nth-child(odd) {
  clear: left;
}
.col-xs-6 {
  border: 1px solid grey;
}
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">

<div class="container">
  <div class="row">
    <div class="col-xs-6">
      Two<br/>
      Lines
    </div>
    <div class="col-xs-6">
      Two<br/>
      Lines
    </div>
    <div class="col-xs-6 label-warning">
      Three<br/>
      Lines<br/>
      Jump
    </div>
    <div class="col-xs-6">
      Two<br/>
      Lines
    </div>
    <div class="col-xs-6">
      Two<br/>
      Lines
    </div>
    <div class="col-xs-6">
      Two<br/>
      Lines
    </div>
  </div>
</div>


Utilizing .clearfix

The recommended approach within Bootstrap involves utilizing the clearfix class which applies specific styles as indicated in Bootstrap's official guidelines:

.clearfix:before,
.clearfix:after {
  content: " ";
  display: table;
}
.clearfix:after {
  clear: both;
}

Note: By combining this with responsive utility classes such as .visible-*-*, .hidden-*, you can selectively target different screen sizes

View Demo in jsFiddle / Stack Snippets:

.col-xs-6 {
  border: 1px solid grey;
}
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">

<div class="container">
  <div class="row">
    <div class="col-xs-6">
      Two<br/>
      Lines
    </div>
    <div class="col-xs-6">
      Two<br/>
      Lines
    </div>
    
    <div class="clearfix"></div>
    
    <div class="col-xs-6 label-warning">
      Three<br/>
      Lines<br/>
      Jump
    </div>
    <div class="col-xs-6">
      Two<br/>
      Lines
    </div>
    
    <div class="clearfix"></div>
    
    <div class="col-xs-6">
      Two<br/>
      Lines
    </div>
    <div class="col-xs-6">
      Two<br/>
      Lines
    </div>
  </div>
</div>


Using .row

An alternative solution involves enclosing each pair of columns in a new row. While less adaptable, this method yields semantically meaningful markup if each set of items constitutes a logical group.

Demo in jsFiddle / Stack Snippets:

.col-xs-6 {
  border: 1px solid grey;
}
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">

<div class="container">
  
  <div class="row">
    <div class="col-xs-6">
      Two<br/>
      Lines
    </div>
    <div class="col-xs-6">
      Two<br/>
      Lines
    </div>
  </div>

  <div class="row">
    <div class="col-xs-6 label-warning">
      Three<br/>
      Lines<br/>
      Jump
    </div>
    <div class="col-xs-6">
      Two<br/>
      Lines
    </div>
  </div>
  
  <div class="row">
    <div class="col-xs-6">
      Two<br/>
      Lines
    </div>
    <div class="col-xs-6">
      Two<br/>
      Lines
    </div>
  </div>
  
</div>


Rectifying Height Discrepancy

In some scenarios, maintaining uniform height across all elements could aid in upholding visual consistency. This strategy works effectively with similar content in each column, fostering a cohesive grid layout.

.col-xs-6 {
  height: 7rem;
}

View Demo in jsFiddle / Stack Snippets:

.col-xs-6 {
  height: 7rem;
}
.col-xs-6 {
  border: 1px solid grey;
}
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">

<div class="container">
  <div class="row">
    <div class="col-xs-6">
      Two<br/>
      line
    </div>
    <div class="col-xs-6">
      Two<br/>
      lines
    </div>
    <div class="col-xs-6 label-warning">
      three<br/>
      lines<br/>
      jump
    </div>
    <div class="col-xs-6">>
      two<br/>
      lines
    </div>
    <div class="col-xs-6">>
      two<br/>
      lines
    </div>
    <div class="col-xs-6">>
      two<br/>
      lines
    </div>
  </div>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What steps can be taken to resolve the error message "AttributeError: 'WebElement' object does not have the attribute 'find_element_class_name'?"

try: main = WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.ID, "main")) ) articles = main.find_elements_by_tag_name("article") for article in articles: header = article.find_element_c ...

Is there a way to achieve horizontal alignment for the Twitter and Facebook buttons on my page?

By utilizing the html code provided, I successfully incorporated Twitter and Facebook "Like" buttons into my website. Initially, they were stacked vertically, which resulted in excessive use of vertical space. To optimize space usage, I decided to align th ...

Rotating a CSS div causes the page to scroll horizontally

Currently, I am working on creating a unique design for the footer of my website. However, when implementing it, I encountered an issue that is causing a horizontal scroll (red background added for clarity). To address this problem and prevent the page fr ...

table: column with percentage-based width AND a minimum width in pixels

Here is an example I'm working with: https://stackblitz.com/edit/js-ivvupc?file=index.html I need my table to be responsive, meaning it should become scrollable when the window size is reduced. The basic setup for this is already in place within the ...

Is there a JavaScript function available that can enable the placeholder attribute to function properly in Internet Explorer?

I currently have numerous input tags in my project that utilize a placeholder attribute, such as the following: <input id="Name" name="Name" placeholder="Name Goes Here" type="text" value=""> Is there a JavaScript function that I can include in my ...

Utilize CSS Steps to incorporate the initial position

I'm experimenting with CSS steps to create a unique visual effect resembling a "light board". The setup involves a column of 18 divs acting as individual "bulbs", with an animation that positions a div behind each one to simulate a "lit up bulb." The ...

Struggling to close the dropdown with jquery

Check out this code snippet: https://jsfiddle.net/rajat_bansal/rtapaew5/1/ The jQuery section below is causing some trouble: $(document).ready(function(e) { $(".sub-handle").click(function() { if(!$(this).hasClass('showing-sub&ap ...

Adding borders to div elements for mobile display

Almost done with my website homepage, but I'm noticing some pesky borders/outlines on mobile devices. This issue doesn't seem to pop up on computers, so you'll need an iPhone, tablet, or smartphone to see what I'm talking about. Check o ...

Select multiple options with personalized text using V-select

Can anyone help me with populating a v-select component from Vuetify 1.5 with checkboxes using multiple? The issue arises when I add <template slot='item' slot-scope='{ item }'></template>. It seems that the checkboxes do no ...

Having difficulties showcasing a variety of images stored in the database

I'm having some trouble with my e-commerce site. I can't seem to display different product images from the database on my homepage. The code I have only shows one image for all products, even though they should each have their own unique image up ...

Employing the Jquery AJAX method to retrieve HTML content

We have a detailed guide on extracting PHP values using Jquery AJAX with JSON data type. Below, you will find the necessary code snippets for implementation. HTML CODE <html> <head> <meta http-equiv="Content-Type" content="text/html; c ...

"Conceal and reveal dynamic content using the power of jQuery's

Hello everyone, I'm encountering an issue with this code where I am trying to display a variable in the content. Take a look at the code below: I am attempting to show the variable $name in the div #divToToggle upon clicking, but the variable does no ...

Deleting Empty Session Data

I have set up sessions for my website. In order to initialize the session, I included the following code on every link of the website: session_start(); if(isset($_SESSION['User'])) { //session_start(); $sesvar = $_REQUEST['sid']; } ...

Shifting the placement of a button with the help of bootstrap

Having a bit of trouble trying to adjust the position of a button inside an input field using bootstrap. The button appears centered within the form field, but I need it to be slightly shifted to the right for design consistency. https://i.stack.imgur.com ...

"Consolidating into one large package, Less is compiled and bundled together

Is there a way to display only the CSS being utilized on a webpage after it loads, rather than serving all compiled .less files as one big .css file? In addition, I am interested in having a sourcemap of the .less files shown in the browser for debugging ...

Enhancing an image with zoom effect in a 2-column layout on hover

Could someone help me achieve a 2-column layout where the left column contains text and the right column an image? I want the image in the right column to zoom when the user hovers over either the left or right column. The issue is that when the user hove ...

Why is it that lists always begin outside of the enclosing element?

I've always found this incredibly frustrating. Why do lists behave this way? When you set the margin and padding to 0, you would expect them to align normally with the surrounding text on the left, right? But no. That's where the text within the ...

What is the most effective way to address duplicate title/meta tags on paginated pages? Can you share some recommended strategies for handling this

Google's webmaster tools are indicating the presence of Duplicate title tags on pages that have pagination. Below are a few examples: HTML suggestions Duplicate title tags Your title provides users and search engines with valuable information about ...

Should servlet response be HTML for use in AJAX calls?

I am currently in the process of developing a web application with multiple pages, including index.html which serves as the main page and contains various <a> tabs linking to different Servlet pages. As part of my design, I have a consistent CSS lay ...

Is it possible for me to develop a mobile application using JavaScript, HTML, and CSS and distribute it for sale on the App Store, Google Play Store, and Microsoft Mobile App Store at

I have a keen interest in web standards such as Javascript, HTML, and CSS. My goal is to utilize these languages to develop applications for mobile devices like phones and tablets. I am also considering selling these applications on various platforms inclu ...