Is there a way to ensure a Bootstrap grid column takes up the entire remaining row space?

I have a dynamic set of elements that need to be inserted into a page, with some elements being labeled as "small" and others as "big". The challenge is that I do not know in advance the quantity or order of these elements.

  • If an element is labeled "small", it should occupy a large col-4.
  • If an element is labeled "big", it should take up as much space as possible within its row, extending from the previous element to the end of the row.

This means that a "big" element could potentially occupy a col-4, col-8, or col-12 size based on its position within the layout. Take a look at this visual representation:

https://i.sstatic.net/X4Uwb.png

The closest question I found on Stack Overflow regarding this issue is: Bootstrap fill remaining columns

I attempted to apply the solution proposed in that question, but it fails when there's a "small" element following a "big" element within the same row. To borrow phrasing from the linked post:

it does not cover the case when, in the same row, you have a blue element after a rogue element

.col-4{
  background:red;
}

.big{
 background:yellow; 
}

.row{
  background:white;
}

 
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e8848988929592928796a6d3c8d6c8d6">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet"/>

<h1>
Expected result
</h1>
The goal is to obtain this same behaviour using the same style for every "big" element

<div class="container-fluid pt-2">
  <div class="row">
    <div class="col-4 mb-1">
      small
    </div>
    <div class="col-4  mb-1">
      small
    </div>
    <div class="col-4  mb-1">
      small
    </div>
    <div class="col-12 big mb-1">
      big
    </div>
    <div class="col-4   mb-1">
      small
    </div>
    <div class="col-4  mb-1">
      small
    </div>


    <div class="col-4 big mb-1">
      big
    </div>
    <div class="col-4  mb-1">
      small
    </div>
    <div class="col-8 big mb-1">
      big
    </div>
    <div class="col-4  mb-1">
      small
    </div>
    

  </div>
</div>

<h1>
Not working attempt 1 (don't use any col)
</h1>
Issue: The "big" elements start on a new row instead of filling the previous row.

...TRUNCATED...

https://jsfiddle.net/bhLq86o4/

How can I assign the same class to all the "big" elements so that the final layout resembles the examples provided?

Answer №1

After experimenting with various layout options like flexbox, grid, and floating elements, I finally discovered a way to achieve the desired outcome where all "big" elements share the same class:

CODE:

.small {
  width: 33.3%;
  float: left;
  background: red;
}

.big {
  background: yellow; 
}
<h1>
  Expected result
</h1>
The aim is to replicate this layout for every "big" element using the same styling

<div>
  <div class="small">
    small
  </div>
  <div class="small">
    small
  </div>
  <div class="small">
    small
  </div>
  <div class="big">
    big
  </div>
  <div class="small">
    small
  </div>
  <div class="small">
    small
  </div>


  <div class="big">
    big
  </div>
  <div class="small">
    small
  </div>
  <div class="big">
    big
  </div>
  <div class="small">
    small
  </div>
</div>

In conclusion: considering this is a challenging task, my suggestion would be to stick to pure CSS rather than getting caught up in unnecessary Bootstrap classes.

Best regards

Answer №2

Avoiding the float Method

The solution provided by @perplexyves may seem correct at first glance, but it is not practical in reality. It appears to work because the example only includes one word per div.

However, if additional content is added, particularly to the second div, the layout will break:

https://i.sstatic.net/76hyc.png

This approach will also encounter various issues (e.g., padding/margins as noticed by OP) since the float layout is more of a superficial workaround than a real grid system.


Embracing the Use of flex

To address each "big" element:

  1. Utilize Bootstrap's .flex-grow-1 class to fill up the remaining row

    (Alternatively, if you prefer using your own .big class, incorporate

    .big { flex-grow: 1 !important; }
    into your CSS)

  2. Include an empty div to signify a line break

<div class="col-4 flex-grow-1">big</div> <div></div>
<!--              ^fill until end           ^move to new row -->

This application of flex creates an authentic grid structure that functions effectively regardless of content or styling:

https://i.sstatic.net/4X5FB.png


Detailed Guide on Using flex

<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e6848989929592948796a6d3c8d4c8d5">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">

<div class="row">
  <div class="col-4 bg-warning">small</div>
  <div class="col-4 bg-warning">This represents the second `div` utilizing the `flex` system. Observing how the grid remains intact even with lengthier/uneven content.</div>
  <div class="col-4 bg-warning">small</div>
  <div class="col-4 bg-danger flex-grow-1">big</div> <div></div>
  <!--                        ^fills till end           ^breaks row -->
  <div class="col-4 bg-warning">small</div>
  <div class="col-4 bg-warning">small</div>
  <div class="col-4 bg-danger flex-grow-1">big</div> <div></div>
  <!--                        ^fills till end           ^breaks row -->
  <div class="col-4 bg-warning">small</div>
  <div class="col-4 bg-danger flex-grow-1">big</div> <div></div>
  <!--                        ^fills till end           ^breaks row -->
  <div class="col-4 bg-warning">small</div>
</div>


Expanded flex Demonstration with Automated Row Breaks

If manually adding empty divs is challenging or unfeasible, implement insertAdjacentHTML for automatic insertion:

document.querySelectorAll('.flex-grow-1').forEach(big =>
  big.insertAdjacentHTML('afterend', '<div></div>'))
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1c7e7373686f686e7d6c5c29322e322f">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">

<div class="row">
  <div class="col-4 bg-warning">small</div>
  <div class="col-4 bg-warning">This is the second `div` using the `flex` layout and employing JS to automatically add empty `div` rows for breaks.</div>
  <div class="col-4 bg-warning">small</div>
  <div class="col-4 bg-danger flex-grow-1">big</div>
  <!--                        ^fills till end           ^row break auto-inserted here via JS -->
  <div class="col-4 bg-warning">small</div>
  <div class="col-4 bg-warning">small</div>
  <div class="col-4 bg-danger flex-grow-1">big</div>
  <!--                        ^fills till end           ^row break auto-inserted here via JS -->
  <div class="col-4 bg-warning">small</div>
  <div class="col-4 bg-danger flex-grow-1">big</div>
  <!--                        ^fills till end           ^row break auto-inserted here via JS -->
  <div class="col-4 bg-warning">small</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

Ways to assign dynamic widths to inner divs within a parent div automatically

I am working with divs <div id='top' > <div id='top-border' > </div> <div id='top-menu' > <jdoc:include type="modules" name="top-menu" style="well" /></div> </div> and adjust ...

Shifted picture next to the accompanying words

I have successfully created a slideshow of images using JavaScript. <html> <head> <script language="JavaScript"> var i = 0; var path = new Array(); path[0] = "one.jpg"; path[1] = "two.jpg"; function swapImage() { document.slide ...

Tips for implementing an HTML modal with AngularJS binding for a pop up effect

As a beginner in AngularJS, I am facing a challenge. I have an HTML page that I want to display as a pop-up in another HTML page (both pages have content loaded from controllers). Using the router works fine for moving between pages, but now I want the s ...

Is it possible to use a while loop to draw and populate a table?

Despite my efforts, this method is not producing the desired outcome. $row2 = 0; while ($row = mysql_fetch_assoc($query)) { echo "<table border='1'>"; if($row2 == 0){ echo "<tr>"; } elseif($row2 < 5){ ...

Organizing flex-items in a specific manner

My goal is to organize flex-items in a specific layout: To achieve this, I am referencing the following example: .Container { display: flex; overflow: hidden; height: 100vh; margin-top: -100px; padding-top: 100px; position: relative; widt ...

Displaying a Bootstrap loading spinner on the right side of a list item

I want to position a Bootstrap loading spinner on the right side of a ui li, with the text "Keywords" on the left side of the ui li. My current HTML code is as follows: <ul class="list-group" id="my-list"> <li class="l ...

React app experiencing issues with Bootstrap offset functionality specifically when paired with a button element

I am struggling to position the button after two columns of space in this code snippet. Despite my efforts, the button remains pulled to the left and I can't seem to update it. { values.contact_persons_attributes.length < 2 && <div className= ...

Enhance the appearance of your forms with the "Bootstrap

I'm having trouble with the input-group-addon class. My HTML code is dynamically generated using JavaScript and follows the same structure across different pages. However, it works on one page but not on another. I can't seem to figure out why! ...

Display a JQuery dropdown menu depending on the ID of the current section

In my one-page structure, I have multiple sections with a categorized nav-bar that includes drop-down lists for each category. My goal is to display the drop-down menu of the category corresponding to the current section. if($("#About").hasClass('act ...

Issue with displaying Bootstrap 3 modal on Mozilla browser

Hello everyone, I've encountered an issue with my Bootstrap modal on Mozilla browser. Everything works perfectly on Chrome and Safari, but when I click the modal button in Mozilla, nothing happens. Here's a snippet of my code: <button type="b ...

Encountered an unexpected character "<" while looking for an identifier in a React.js project

Looking to expand my React skills, I decided to delve into a basic e-commerce project using Visual Studio. Unfortunately, I encountered some errors along the way: E-commerce Project Errors Here is a snippet of my index.js code: code snippet Any insight ...

What is the best way to make a JavaFX WebView the same size as the entire scene?

My goal is to have a JavaFX WebView that automatically resizes to fit the scene upon startup. Currently, I am focused on setting the initial size properly. @Override public void start(Stage stage) { try { Scene scene = new Scene(createWebViewP ...

Design featuring a fixed top row and a scrollable bottom row

I need to divide a div container into two vertical sections, one occupying 60% of the space and the other 40%. The top div (60%) should always be visible, while the bottom div (40%) should be scrollable if it exceeds its limit. I have tried different app ...

Please refer to the appropriate manual for your MySQL server version to find the correct syntax for the following statement: `'' , , '', '', '', '', '', '', NOW())' at line 2`

I encountered an error and since I am new to programming, I would appreciate any corrections. Thank you! <? $customername = $_REQUEST["customername"]; //$customername = strtoupper($customername); //$customername = trim($customername); $address1=$_RE ...

Develop a circular carousel using React JS from scratch, without relying on any third-party library

I am looking to replicate the carousel feature seen on this website. I want to mimic the same functionality without relying on any external libraries. I have found several resources explaining how to achieve this. Most suggest creating duplicate copies o ...

Adding a border to the input field in Bootstrap for enhanced styling and visibility

Looking to replicate the border style on an input element as shown in this image: https://i.sstatic.net/a2iwZ.png The current code I have is producing a different result. Can anyone assist me in achieving the desired border style? <!DOCTYPE html> ...

What is the best way to assign the "active" class to a navigation list item using JavaScript within Bootstrap 4?

Update: just to clarify, I'm working on activating the navbar button based on the current page. I have a navigation bar set up and I am trying to dynamically add an "active" class to the li element when you are on that specific page. However, for som ...

Incorporating Ajax comments into an Ajax-powered status feature

I'm currently in the final phase of implementing ajax in my feed. Originally, I thought it would be a simple matter of pasting the comment input, but it turned out to be more complex than I anticipated. I placed the input below the main ajaxed status ...

Display the X button solely once text has been inputted into the textbox

I have integrated a text clearing plugin from here in my project to allow users to clear the input field by clicking on an X button. However, I want to modify the code so that the X button only appears when there is text entered in the textbox. I attempt ...

Can we resize the button to match the width of the blue bar?

.nav-info { height: auto; background-color: darkblue; color: white; padding: 1em; padding-left: 5%; flex-direction: row; justify-content: space-between; } .flexbox { display: flex; } .info a { color: white; text-decoration: none; fo ...