Bootstrap for arranging DIVs in a responsive manner

I am trying to place some DIV elements inside their parent container, whether it is the body, a table's cell, or another div, using Bootstrap 5. The desired layout is shown on the attached illustration:

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

If there is an even number of DIV elements, they should each take up 50% of the available width and be positioned in pairs on a single line. If there is an odd number of DIV elements, the last one should take up 100% of the available width while the previous ones still take up 50% each and are positioned in pairs on a single line.

It would be ideal to have the flexibility to change the order of the DIV elements, similar to the Mobile View example.

I know that achieving this layout with UIKit is relatively straightforward using code like:

<div class="uk-grid">
    <div class="uk-width-large-1-2">DIV 1 takes 50% of available width</div>
    <div class="uk-width-large-1-2">DIV 2 takes 50% of available width</div>
    <div class="uk-width-large-1-2">DIV 3 takes 100% of available width</div>
</div>

However, I have been unable to find a solution for achieving the same layout using Bootstrap's documentation or on Stack Overflow.

Answer №1

When working with Bootstrap, it follows a mobile-first approach. This means that whatever styling is defined for smaller breakpoints will automatically apply to larger breakpoints unless explicitly overridden.

There are 5 specific breakpoints in addition to the default mobile breakpoint:

| Breakpoint | Dimensions
|------------|----------- 
| NONE       | <576px
| sm         | ≥576px
| md         | ≥768px
| lg         | ≥992px
| xl         | ≥1200px
| xxl        | ≥1400px

Resizing Div Elements

To resize div elements, you can utilize Bootstrap's responsive column classes as shown below:

<div class="row g-2">
  <div class="col-12 col-md-6">...</div>
  ...
</div>
  • col-12 makes the column full width (12 out of 12) on mobile and larger screens
  • col-md-6 makes the column half width (6 out of 12) on medium screens and larger, overriding the col-12 rule
  • g-2 adds gutters to the columns for padding or you can use spacing utilities for manual spacing

The order in which the classes are written, such as col-12 col-md-6 or col-md-6 col-12, doesn't matter as Bootstrap applies styles in a mobile-first manner.


Auto-Expanding the Last Div

What if you do not know the number of divs inside a row, making it uncertain if the last div will be odd or even? How do you ensure that the last div always spans 100% width inside the container?

If working with a templating language like Django, you can implement this logic in the template. For instance:

<div class="row">
  {% for col in cols %}
  <div class="col-12{% if loop.last and not forloop.counter|divisibleby:2 %} col-md-6{% endif %}">
    ...
  </div>
  {% endfor %}
</div>

Alternatively, you can achieve this using pure CSS by targeting the last col if it's an odd one:

.row > .col-md-6:last-child:nth-child(odd) {
  width: 100%;
}

Reordering Div Elements

For reordering div elements, utilize Bootstrap's flex order utilities:

<div class="row">
  <div class="order-2 order-md-1">...</div>
  <div class="order-1 order-md-2">...</div>
  ...
</div>
  • order-2 order-md-1 positions the element as 2 on mobile screens and 1 on medium screens and larger
  • order-1 order-md-2 positions the element as 1 on mobile screens and 2 on medium screens and larger

Keep in mind that the parent container needs to be a flex container. While a Bootstrap row is flex by default, you can explicitly add the d-flex class for non-flex containers.


Minimal Example

https://i.sstatic.net/mUgEL.png https://i.sstatic.net/jqr6A.png

.row > .col-md-6:last-child:nth-child(odd) {
  width: 100%;
}
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="94f6fbfbe0e7e0e6f5e4d4a1baa4baa6">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet">

<body class="bg-secondary">
  <div class="container pt-3">
    <div class="row g-2">
      <div class="col-12 col-md-6 order-2 order-md-1">
        <div class="bg-light text-center p-2">DIV 1</div>
      </div>
      <div class="col-12 col-md-6 order-1 order-md-2">
        <div class="bg-light text-center p-2">DIV 2</div>
      </div>
      <div class="col-12 col-md-6 order-3">
        <div class="bg-light text-center p-2">DIV 3</div>
      </div>
      <div class="col-12 col-md-6 order-4">
        <div class="bg-light text-center p-2">DIV 4</div>
      </div>
      <div class="col-12 col-md-6 order-5">
        <div class="bg-light text-center p-2">DIV 5</div>
      </div>
    </div>
  </div>
</body>

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

Use VueJS v-on:click and Vanilla JS to collapse various divs when clicked

Can VueJS and vanilla JS be used to collapse specific divs among many? I have information contained in separate card elements that include a title and a body. My goal is to make the body of each card expand or collapse when the respective title is clicked ...

Exclude the UL hierarchy from removing a class in jQuery

Check out this fiddle to see the code snippet: http://jsfiddle.net/3mpire/yTzGA/1/ I am using jQuery and I need to figure out how to remove the "active" class from all LIs except for the one that is deepest within the hierarchy. <div class="navpole"&g ...

What causes certain properties of html and body elements to behave in this way?

I'm on a quest for understanding some mysteries. First riddle: Why does the body have a mysterious margin-top? html { height: 100%; background-color: red; } body { height: 100%; margin: 0; background-color: yellow; } <h1>Hello P ...

Remove the color gradient for the column headers in the Google Visualization table

Whenever I attempt to change the colors of the column headers using the method demonstrated in this insightful source, a rather generic gradient is applied. Interestingly, the example code provided also demonstrates the same default gradient on the secon ...

Keyframes and CSS Animation for Border Effects

I've been struggling to achieve a specific animation that I can't seem to get right. Despite searching online for solutions, none of them quite match the desired effect. What I'm looking for is a border animation that starts at the bottom l ...

Is it possible to create a CSS checkbox without using an ID or "for" attribute

Is it possible to create a CSS checkbox with label without using id and for attributes? I have tried the following method, but it doesn't seem to work. I know that I can create a CSS checkbox with id and for attributes like this: <div class="chec ...

Dividing a pair of CSS stylesheets on a single HTML page

Currently, I am working on a HTML page that includes multiple javascripts and css files in the header section. <link href="@Url.Content("~/Content/css/main.css")" rel="stylesheet" type="text/css" /> In order to make the website mobile-friendly, I s ...

Element Style Does Not Align with Computed Z-Index

Currently, I am in the process of developing an HTML5 video player. However, I have encountered a problem where my custom controls become unclickable once the video element is set to fullscreen mode. This issue arises because the video's z-index is se ...

Firefox and IE are unable to make changes to cssRules

To update existing global CSS rules, I access the document.styleSheets property to locate the rule and make modifications. The selector can be modified by accessing the selectorText property. Sample CSS code: <style type="text/css"> .class { ...

What is the method for stretching the navbar and content to fill the entire viewport in Bootstrap?

Can anyone help me with an issue regarding a navigation bar and content created in Bootstrap 5? I'm trying to use vh-100 to make both the navigation bar and content stay on the view page without a scrollbar. However, the size of the navigation bar is ...

Create a box with borders and divisions using HTML

Hello, I am trying to create a box in HTML with a slanted divider line inside. How can I achieve this design? I am aiming to replicate the layout shown in this image: Link to Image I have tried implementing the code below, but the alignment is not matchi ...

Implementing a hamburger menu and social media sharing buttons on websites

Currently working on my personal website and delving into the world of Web Development, I have some inquiries for seasoned developers. My first query revolves around incorporating a hamburger menu onto my site for easy navigation to other pages. After att ...

Problem encountered with HTML table formatting

I am struggling to create a table in HTML Click here for image Here is the code I have tried: <table> <tr> <th class="blue" colspan="3">3</th> <th class="orange " rowspan="2">2</th> <th class="blu ...

Using the bootstrap-vue library to create a dropdown menu within a div element

Bootstrap-vue is not really my favorite, and I'm having some issues. Is it possible to create something like this without using bootstrap-vue? <div class="dropdown open"> <div data-toggle="dropdown" class="dropdown-toggle">some text&l ...

Animating CSS Pixel Fragments

After applying a simple CSS animation that moves size and box shadows from one side of the screen to the other, I am noticing residual pixel fragments left behind. To see this issue in action on Chrome 66, check out the Code Pen: https://i.sstatic.net/Gl ...

Managing text size in HTML email designs

How can I maintain consistent font sizes in HTML EMAILS? The fonts look great on the website, but in my email they appear small and close together. Check out Live Demo I've attached a screenshot of how the email appears to me. Any suggestions on h ...

Modify the pseudo element when a different class is active

I've encountered an issue while attempting to modify the after pseudo element when the .active class is applied. Despite my efforts, it doesn't seem to be functioning as intended. My current project setup involves using scss with Vue. I have tri ...

JavaScript animation is not functioning as expected

I created a div with the id of "cen" and gave it a height and width of 50px. $(document).ready(function() { $("#cen").animate({ height: 500px, width: "500px", }, 5000, function() { // Animation complete. }); }); Unfort ...

Trouble with applying CSS class to checkboxlist

I am trying to display a border around each checkbox item in a checkboxlist. I believe that it can be achieved by setting the td cssclass as the checkboxlist saves items in td. However, the code I tried below is not working. Here is the ASPX code: < ...

Do you require a lightbox for a white text box set against a semi-transparent black background?

Currently, I am in the process of developing a Chrome extension that will be compatible with my Android app. As part of this development, I need to code the HTML/CSS for the extension. The main functionality of the extension allows users to add tags to a s ...