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?

Mateusz Piotrowski
  • 8,029
  • 10
  • 53
  • 79
ApathyBear
  • 9,057
  • 14
  • 56
  • 90

3 Answers3

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

Carol Skelly
  • 351,302
  • 90
  • 710
  • 624
  • 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 07 '16 at 17:13
  • Basically `center-block` would only work on a `display:block` element – Carol Skelly Jul 07 '16 at 17:27
  • 1
    For future readers it seems like `m-x-auto` is renamed to `mx-auto` fram alpha.5 – Ole Kristian Losvik Nov 09 '16 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 '17 at 06:13
7

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

Rory O'Kane
  • 29,210
  • 11
  • 96
  • 131
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.

Greg Gum
  • 33,478
  • 39
  • 162
  • 233