Guide to perfectly aligning a Bootstrap 4 toolbar

I've been trying to horizontally center a toolbar without success. Despite trying various solutions, nothing seems to work in bootstrap 4.

The closest solution I found requires setting a width which doesn't really center the toolbar. Since the number of items in the toolbar may vary, it will never be truly centered. How can I properly achieve a centered toolbar?

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

<head>
<meta charset="utf-8>
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no>

<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous></script>

<link href="css/bootstrap.min.css" rel="stylesheet> 
<link href="css/main.css" rel="stylesheet> 
</head>

<body class="bg-secondary>
<div class="mx-auto" style="width: 300px; background:red>
Centered element<br/>
<div class="btn-toolbar mx-auto" role="toolbar>
<div class="btn-group mr-2" role="group" aria-label="First group">
<button type="button" class="btn btn-primary>1</button>
<button type="button" class="btn btn-primary>2</button>
<button type="button" class="btn btn-primary>3</button>
<button type="button" class="btn btn-primary>4</button>
</div>
</div>
</div>
</body>

</html>

Edit: this is not a duplicate of [. That question is about a navbar, not a toolbar, in a container. I have seen that question while searching but I don't see how it applies to the html presented. https://i.sstatic.net/3MeIx.png

Answer №1

There are various methods to achieve this. One option is to set the toolbar display property to inline-block (d-inline-block) and apply text-center to the parent element.

https://www.example.com/code-sample

   <div class="text-center">
      <div class="d-inline-block" style="background:red">
            Centered element<br/>
            <div class="btn-toolbar mx-auto" role="toolbar">
                <div class="btn-group mr-2" role="group" aria-label="First group">
                    <button type="button" class="btn btn-primary">1</button>
                    <button type="button" class="btn btn-primary">2</button>
                    <button type="button" class="btn btn-primary">3</button>
                    <button type="button" class="btn btn-primary">4</button>
                </div>
            </div>
        </div>
     </div>

Another approach is to utilize flexbox and use justify-content-center on the parent element with the class d-flex

<div class="d-flex justify-content-center">
    <div class="btn-toolbar mx-auto" role="toolbar">
        <div class="btn-group" role="group" aria-label="First group">
            <button type="button" class="btn btn-primary">1</button>
            <button type="button" class="btn btn-primary">2</button>
            <button type="button" class="btn btn-primary">3</button>
            <button type="button" class="btn btn-primary">4</button>
        </div>
    </div>
</div>

Answer №2

If you're looking for an alternative solution, consider including justify-content-center in your btn-toolbar like this:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/css/bootstrap.min.css" integrity="sha384-Zug+QiDoJOrZ5t4lssLdxGhVrurbmBWopoEl+M6BdEfwnCJZtKxi1KgxUyJq13dy" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/js/bootstrap.min.js" integrity="sha384-a5N7Y/aK3qNeh15eJKGWxsqtnX/wWdSZSKp+81YjTmS15nvnvxKHuzaWwXHDli+4" crossorigin="anonymous></script>

<div class="container-fluid">
  <div class="row">
      <div class="col-12" style="background:red">
    
        <div class="btn-toolbar justify-content-center" role="toolbar" aria-label="Toolbar with button groups">
          <div class="btn-group mr-2" role="group" aria-label="First group">
          <button type="button" class="btn btn-secondary">1</button>
          <button type="button" class="btn btn-secondary">2</button>
          <button type="button" class="btn btn-secondary">3</button>
          <button type="button" class="btn btn-secondary">4</button>
        </div>

        <div class="btn-group mr-2" role="group" aria-label="Second group">
          <button type="button" class="btn btn-secondary">5</button>
          <button type="button" class="btn btn-secondary">6</button>
          <button type="button" class="btn btn-secondary">7</button>
        </div>
        
        <div class="btn-group" role="group" aria-label="Third group">
          <button type="button" class="btn btn-secondary">8</button>
        </div>
        
    </div>
  </div>
</div>

Avoid the need for wrappers or using inline-block by simply adding justify-content-center.

Answer №3

To easily center elements, consider using flexbox. It's recommended to wrap your text within a p tag instead of just a div tag.

.mx-auto {
  display: flex;
  height: 100%;
  flex-direction: column;
  align-self: center;
}

p {
  align-self: center;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8>
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

  <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>

  <link href="css/bootstrap.min.css" rel="stylesheet">
  <link href="css/main.css" rel="stylesheet">
</head>

<body class="bg-secondary">
  <div class="mx-auto" style="width: 300px; background:red">
    <p>Centered element</p><br/>
    <div class="btn-toolbar mx-auto" role="toolbar">
      <div class="btn-group mr-2" role="group" aria-label="First group">
        <button type="button" class="btn btn-primary">1</button>
        <button type="button" class="btn btn-primary">2</button>
        <button type="button" class="btn btn-primary">3</button>
        <button type="button" class="btn btn-primary">4</button>
      </div>
    </div>
  </div>
</body>

</html>

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

The clear both property in CSS has an impact on the layout flow

Why is the placement of the <h1> tag with "clear both" at the bottom causing issues? Removing "clear both" resolves the problem, but how can I make it work when including "clear both"? <!DOCTYPE html> <html> <head> <meta http- ...

Differences between JavaScript's window.onload and body.onload functionsWhen

My inquiry is similar yet slightly distinct from the one queried here: window.onload vs <body onload=""/> The comparison in that prior query was between utilizing window.onload and inline js. My question pertains to the disparity between ...

Properly arrange the positioning of floating HTML elements

I am currently using the float property to structure the layout. <style> div { float: left; } .pro { width : 100px; color : blue; } </style> <span> <div class="pro">Long property name : </div> <div>value&l ...

What is the method for extracting element.style.marginTop in digits exclusively?

Consider an HTML element with the property margin-top: 30px. function extractValue(margin) { /* to do */ } var element = document.getElementById("element"); alert(extractValue(element.style.marginTop)); #element { margin-top: 30px; } <div id=" ...

Modal failing to update with latest information

My webpage dynamically loads data from a database and presents it in divs, each with a "View" button that triggers the method onclick="getdetails(this)". This method successfully creates a modal with the corresponding data. function getdetails(par) { ...

Creating a lifelike sinusoidal flag animation or flutter effect using SVG格式

I'm attempting to create a lifelike animated svg flag that flutters in the wind. Currently, I am using this simple flag base: <svg xmlns="http://www.w3.org/2000/svg" width="200px" height="100px" viewBox="0 0 200 100" > <p ...

Issue with display of absolute/relative positioned element in IE8

Within a list element (a div) styled with inline-block, there is a ul positioned relatively that is initially hidden. To make the div absolute, I added a class but encountered issues specifically in IE8/9 where clicking on the list does not reveal it as ex ...

Tips on altering the quantity of columns in a ul list dynamically

I'm trying to create a list with 2 columns, and I want it to switch to 3 columns when the browser window is wide enough (for example, on a 23 inch monitor). Can this be achieved using CSS or any other method? Here is my current CSS: .search-results ...

Tips on Switching the Font Family in Bootstrap

Can someone please explain to me how to change the font family in Bootstrap? I looked for the answer and came across this link: . The link provides some guidance, but I'm still struggling to understand how to do it in simple terms. Even though there i ...

Using Jquery to toggle a class on click, and dynamically change based on the screen size

I am trying to figure out how to toggle a CSS class on an element by clicking on a div using jQuery. I know how to do it, but I also want the toggle to only happen when the screen size is less than 800px. I'm not very familiar with JavaScript, so I co ...

How is the script type "text/html" utilized in contemporary applications? Is this specific example regarded as effective usage?

Is it considered good practice in today's standards to utilize something like the following code snippet and use jQuery to swap out content based on a selector? <script type="text/html" id="this-content1"> <h1>This Header Info One</h1& ...

Ways to make Selenium detect and interact with a button for clicking:

Is there a way for selenium python to identify this specific button within the HTML code? I've experimented with various tags but have been unsuccessful. driver.find_element_by_class_name('cookie-monster').clickbutton print('s ...

Sass/SCSS is failing to compile on my local environment

As a beginner in SASS, I'm currently attempting to compile my SASS file on my local machine. Unfortunately, I've hit a roadblock and despite trying all the methods mentioned, I continue to encounter the same or similar errors. It's frustrati ...

Web Page Layout Altered on Smaller Screen with Internet Explorer 6

After designing an ASP.NET web page on a widescreen monitor with IE10, I was surprised to see it looking completely different when opened on a regular (non-widescreen) monitor running IE6. While the functionality remained intact, some transparency effect ...

Is there a way to overlap shapes (transform) using ::before and ::after in CSS? I'm facing an issue where Edge is not showing the shape on top

I designed two diagonal shapes to overlay a container with a background image using the pseudo elements ::before and ::after. While this setup functions correctly in Firefox and Chrome, it is not working as expected in Edge. What could be causing this di ...

Javascript - Button animation malfunctioning after first click

One issue I'm facing is with an animation that is triggered using the onmousedown event. Another function is supposed to stop the animation when onmouseup is detected. The problem arises after the first time it works correctly. Subsequent attempts to ...

Located just above the edge of the screen with absolute positioning

One of the features on my website is a small modal that smoothly slides in from the top of the page upon entering, and then slides back out again when clicked on. However, I am encountering an issue where I do not want the modal to completely disappear aft ...

Having trouble with the ng-class syntax?

I've been diving into the world of Angular.js and came across this code snippet: <button ng-class="{'btn pull-left', duplicatesInList === true ? 'btn-warning': 'btn-success'}" id="saveScoreButton" type="button" ng-c ...

Verify whether a group of div elements overlaps a fixed div while scrolling

I have a layout with a list of posts and a logo positioned at the bottom of the page. The issue I am facing is that sometimes the title of the posts and the logo overlap, and I want to set the logo's opacity to 0.25 only when the text from .cat-date i ...

Creating Dynamic Height for Div Based on Another Element's Height Using ReactJS and CSS

I'm attempting to set a fixed height for a div in order to enable overflow scrolling. However, I am encountering issues as I am using JavaScript within a useEffect hook to accomplish this task. The problem is inconsistent as sometimes the height is se ...