25

I have the following bootstrap html code (its JSX hence the className but the idea is the same):

<div className="toggleView btn-group center-block" role="group" aria-label="Basic example">
        <button onClick={this.handleTimelineClick} type="button" className={this.state.toggleCalendar == false ? "btn btn-secondary active" : "btn btn-secondary"}>Timeline</button>
        <button onClick={this.handleCalendarClick} type="button" className={this.state.toggleCalendar == true ? "btn btn-secondary active " :"btn btn-secondary"}>Calendar</button>
 </div>

I am trying to center this code with either bootstrap center-block or with CSS but cannot seem to get it to work:

enter image description here

The green bar highlights the div toggleView.

The only css I am using is the following:

.toggleView {
    padding: 20px;
}

Why can I not center this button group?

3 Answers 3

56

btn-group has display:inline-block so you would use text-center in the parent container..

http://codeply.com/go/hyUYkUrtRN

NOTE: In Bootstrap 4, center-block is now mx-auto, representing margin: 0 auto; for centering display:block elements. Bootstrap 4 now has a d-block class too so an inline element can be made display:block like this..

<img src=".." class="d-block mx-auto" >

Also see: Center the content inside a column in Bootstrap 4

4
  • 1
    Thank you, this is a bit confusing to me why this works though. Can you discuss a little more about display:inline-block and what that is actually doing and how text-center solved this problem?
    – ApathyBear
    Jul 7, 2016 at 17:13
  • Basically center-block would only work on a display:block element Jul 7, 2016 at 17:27
  • 1
    For future readers it seems like m-x-auto is renamed to mx-auto fram alpha.5 Nov 9, 2016 at 21:19
  • What I found in Bootstrap v4.0.0-alpha.6. mx-auto has only two values, margin-left: auto !important and margin-right: auto !important. vertical-middle class worked for me.
    – Jonas T
    Jan 23, 2017 at 6:13
7

Bootstrap 4 (as of 2017-08-16) will use d-block and to center you use mx-auto.

1
  • Unless the element has a defined width it does not work at all.
    – Kyobul
    Dec 17, 2018 at 1:01
6

Bootstrap 4 does not have center-block Instead, I use d-block mx-auto which sets display to block, and left and right margins to auto.

2
  • This is now d-block mx-auto
    – Roger
    Oct 11, 2018 at 22:31
  • @Kyobul, Are you sure? It has worked for me. Can you post an example?
    – Greg Gum
    Dec 17, 2018 at 12:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.