Make sure to employ Bootstrap's justify-content-between and stack-to-horizontal col correctly

I am currently working on a responsive form that contains 1 label, 1 input field, and 5 buttons.

Both the buttons and the input field are located under col-8.

The positioning I aim for the buttons is as follows:

  1. They should start below and align with the input field location. (think of them as 2 rows under a col-8)

  2. Equal spaces between each pair of buttons.

  3. On smaller screens, the buttons should be displayed stacked.

Attached are screenshots exemplifying my desired outcome:

View for regular screens

View when on smaller screens - they should appear in a stack

Below is the code snippet I have been using:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <!-- CSS only -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
    <!-- JS, Popper.js, and jQuery -->
    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8afae5fafaeff8a4e0f9cabba4bbbca4bb">[email protected]</a>/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script>
  </head>
  <body>
    <div class="container bg-dark col-6" style="margin-top: 2rem;">
      <form>
        <div class="form-group row">
          <label for="id" class="col-4 col-form-label" style="color: white;">id</label>
          <div class="col-8">
            <input id="id" name="id" type="text" class="form-control">
          </div>
        </div>
        <div class="offset-4 form-group row justify-content-between">
          <button type="button" class="btn btn-primary">A</button>
          <button type="button" class="btn btn-warning">B</button>
          <button type="button" class="btn btn-primary">C</button>
          <button type="button" class="btn btn-danger">D</button>
          <button type="button" class="btn btn-info">E</button>
        </div>
        <div class="offset-4 form-group row">
          <div class="col-sm">
            <button type="button" class="btn btn-primary">A</button>
          </div>
          <div class="col-sm">
            <button type="button" class="btn btn-warning">B</button>
          </div>
          <div class="col-sm">
            <button type="button" class="btn btn-primary">C</button>
          </div>
          <div class="col-sm">
            <button type="button" class="btn btn-danger">D</button>
          </div>
          <div class="col-sm">
            <button type="button" class="btn btn-info">E</button>
          </div>
        </div>
        <div class="offset-4 form-group row justify-content-between">
          <div class="col-sm">
            <button type="button" class="btn btn-primary">A</button>
          </div>
          <div class="col-sm">
            <button type="button" class="btn btn-warning">B</button>
          </div>
          <div class="col-sm">
            <button type="button" class="btn btn-primary">C</button>
          </div>
          <div class="col-sm">
            <button type="button" class="btn btn-danger">D</button>
          </div>
          <div class="col-sm">
            <button type="button" class="btn btn-info">E</button>
          </div>
        </div>
      </form>
    </div>
  </body>
</html>

I have attempted three different ways to position the 5 buttons.

  1. Initially - utilizing row and justify-content-between
  2. Next - adding row and col
  3. Lastly - incorporating row, col, and justify-content-between

Unfortunately, each method either exceeds the width of the input field (as shown in the first screenshot) or leaves space from the input field's width (as seen in the second screenshot).

How can I properly arrange the 5 buttons to meet both the requirements of justify-content-between and stack [ col within row ] efficiently?

A kind request: Could you suggest an approach that minimizes the excessive use of margin and padding, ensuring compatibility across all screen sizes?

Answer №1

It seems there are a few issues with your markup. To prevent these in the future, I recommend carefully reviewing each bullet point in the How it works section of the Bootstrap grid documentation.

Here's a summary of the issues found:

  • Some of the .row elements were not direct children of .container or .col, causing alignment problems due to negative margins. Ensure that the parent has horizontal padding to compensate for the negative margins, or use classes like mx-0 or no-gutters.
  • The class .offset-4 was incorrectly applied to a .row instead of .col, resulting in misaligned columns within the row.
  • You don't need an additional set of nested .row + .col to use .justify-content-between; simply apply d-flex class directly to the element.

To offer an alternative solution, I've updated the last example using a .btn-group, which provides a cleaner layout for action bars. The custom CSS included adjusts the layout for mobile responsiveness.
See the updated implementation below:

.custom-btn-group {
  width: 100%;
}

@media(max-width: 767px) {
  .custom-btn-group,
  .vertical-mobile {
    flex-direction: column;
  }
  .custom-btn-group:not(#_) .btn {
    margin-left: 0;
  }
  .custom-btn-group:not(#_) .btn:first-child {
    border-top-right-radius: .25rem;
    border-bottom-left-radius: 0;
  }
  .custom-btn-group:not(#_) .btn:last-child {
    border-bottom-left-radius: .25rem;
    border-top-right-radius: 0;
  }
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
<!-- JS, Popper.js, and jQuery -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script>


<div class="container">
  <div class="row">
    <form class="bg-dark col-sm-6 py-3">
      ... (remaining HTML structure goes here)
    </form>
  </div>
</div>

Answer №2

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <!-- CSS only -->
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
  <!-- JS, Popper.js, and jQuery -->
  <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5c2c332c2c392e72362f1c6d726d6a726d">[email protected]</a>/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script>
</head>

<body>
  <div class="container bg-dark col-6" style="margin-top: 2rem;">
    <form>
      <div class="form-group row">
        <label for="id" class="col-4 col-form-label" style="color: white;">id</label>
        <div class="col-8">
          <input id="id" name="id" type="text" class="form-control">
        </div>
      </div>
      <div class="row">
        <div class="offset-4 col-8">
          <div class="row justify-content-between" style="margin: 0%; padding: 0%;">
            <div class="col-auto" style="margin: 0%; padding: 0%;">
              <button name="button" type="button" class="btn btn-primary">A</button>
            </div>
            <div class="col-auto" style="margin: 0%; padding: 0%;">
              <button name="button" type="button" class="btn btn-success">B</button>
            </div>
            <div class="col-auto" style="margin: 0%; padding: 0%;">
              <button name="button" type="button" class="btn btn-warning">C</button>
            </div>
            <div class="col-auto" style="margin: 0%; padding: 0%;">
              <button name="button" type="button" class="btn btn-danger">D</button>
            </div>
            <div class="col-auto" style="margin: 0%; padding: 0%;">
              <button name="button" type="button" class="btn btn-primary">E</button>
            </div>
          </div>
        </div>
      </div>
    </form>
  </div>
</body>

</html>

Some strategies that proved successful for me:

  1. To eliminate any gaps, I consistently applied margin: 0% and padding: 0% to each instance of col-auto.
  2. I organized each button within a col-auto, then grouped each col-auto in a row. The final step involved setting the row's alignment to justify-content-between, along with ensuring margin: 0% and padding: 0% to prevent unnecessary spacing.
  3. Ultimately, I enclosed the entire setup within offset-4 col-8, which was nested under a row.

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

Using htaccess to redirect all html pages to php except for one

My website is configured to redirect all html pages to php using htaccess rules: RewriteEngine On RewriteBase / RewriteCond %{HTTP_HOST} ^website.com RewriteRule (.*) http://www.website.com/$1 [R=301,L] RewriteRule ^(.+)\.html$ http://www.website.c ...

The use of pattern fill in fabric.js is causing a decrease in rendering speed

I recently attempted to create a clip mask effect on a large image by using the picture as a pattern and setting it to the svg paths that support the desired shape. You can view the slow-loading jsfiddle example here: http://jsfiddle.net/minzojian/xwurbw ...

What is the best way to incorporate a div below an image in Ubergallery?

I have integrated the jquery ubergallery into my website, and I am trying to add a new div below the main photos for additional content such as share buttons and comments. I tried using the code that worked with colorbox, but since ubergallery uses colorbo ...

Retrieve the file path of an uploaded image in a Razor view using jQuery Ajax

I have been facing challenges while working on an ASP.NET MVC3 application where I am developing a custom image gallery. The browser being targeted is IE9, which rules out the option of using HTML5 File API. All my code resides within a strongly typed Razo ...

Is it possible to detach keyboard events from mat-chip components?

Is there a way to allow editing of content within a mat-chip component? The process seems simple in HTML: <mat-chip contenteditable="true">Editable content</mat-chip> Check out the StackBlitz demo here While you can edit the content within ...

Tips for adjusting column sizes in react-mui's DataGrid based on screen size

I would like the title column to occupy 3/4 of the full row width and the amount column to take up 1/4 of the full row width on all screens sizes (md, sx...). Here is the updated code snippet: import React from 'react' const MyComponent = () =&g ...

Using the PUT method in Node.js to set the ID

Need help with setting ID value from frontend apiRoutes.put('/intake', function(req, res) { Intake.findById({id, function(err, intake) { if (err) res.send(err); check : true; intake.save(function(err) { ...

Preventing the elements within a div section from shifting position

I am facing an issue with a div section that contains multiple <a href=""> tags. When I shrink the div section on the page, the contents move when a user tabs into it. Is there a way to lock the div section so that its contents do not move? For exam ...

Is it possible to create a responsive Material UI tab design?

How can I make the Material UI tab react component responsive? Check out the documentation for MATERIAL UI TAB here If I have multiple tab items with a search bar like shown below, how can I ensure that the input component stretches the whole width of th ...

I'm having trouble with my bootstrap dropdown and I've exhausted all of my options trying to fix it based on my current understanding

My dropdown menu is not working despite adding all necessary Bootstrap CDN and files along with the jQuery script. Even with the table being handled by JavaScript, the button does not respond when clicked repeatedly. I suspect the issue lies within the han ...

Bootstrap 4.0. When it comes to buttons, they seem to have trouble cooperating with other DIV elements

Today is my first time seeking help on StackOverflow: I'm encountering an issue with my website where the floating arrow at the bottom of the page is obstructing my ability to click on buttons. Whether it's a Bootstrap button or HTML button, non ...

Styling the elements that are next to each other using CSS

Hey there, what if I have HTML elements structured like this: <div> <div>Name</div> <div><input type="text" class="check"> <div>Age</div> <div><input type="number" class="check"></div> ...

Having trouble correctly parsing XML data using JavaScript

My input field contains the following XML code: <?xml version="1.0" encoding="utf-8"?> <players timestamp="1536505850"> <player id="0518" name="Eagles, Philadelphia" position="Def" team="PHI" /> <player id="10271" name="Jones, Jul ...

What can be done to repair the gallery on this webpage?

Currently, I am experimenting with the Aria template, a free Bootstrap-based template. My goal is to utilize the gallery feature without any accompanying text. However, even after removing the text from the lightbox, the white background persists. What I s ...

Adjusting the Aspect Ratio of an Embedded YouTube Video

<!DOCTYPE HTML> <head> <style> body { overflow: hidden; margin:0; } </style> </head> <body> <iframe id="video" src="https://www.youtube.com/embed/U4c9bBeUe4M?modestbranding=1&sh ...

How to Programmatically Assign Bootstrap Class to an Element Using Angular 2

I am working on a page with several input boxes that need to be flagged for certain criteria. <div class="form-group"> <label class="d-block">Allowance Type</label> <div class="input-group"> ...

The CSS Grid container fails to resize based on the content inside

I am facing an issue with the grid element inside a parent container with display: grid;. The parent container has a maximum size and allows scrolling for the grid if necessary. The problem is that the grid element does not expand to fit its children. Whe ...

Troubleshooting display problems with the categories menu in Opencart version 1.5.1 caused by IE

For our opencart website, we utilize the li element for the sub categories items. displays properly on all modern browsers. However, we need to ensure compatibility with Internet Explorer 6 as well. ...

Strong tags are not functioning properly within paragraph tags in Firefox

It has come to my attention that when I insert <strong> into a <p>, the text does not appear bold. This issue seems to only occur in Firefox, as Chrome and Safari display it correctly. However, when I place <strong> inside a <li>, e ...

Using jQuery to retrieve child elements and assign numerical values to them

Looking for a jQuery function that can apply different CSS attributes to children elements of a div. <div class="container"> <div class="autogenerated-div"></div> <div class="autogenerated-div"></div> <div class="aut ...