Search code examples
cssflexboxalignment

putting button at center of div


I want to put a button at the center of a div (both vertically and horizontally).

Here: CSS: center element within a <div> element

the approved answer says that this code:

#button_div {
  display: flex;
  align-items: center;
  justify-content: center;
}

would achieve this. Applying this code, the button is entered vertically but not horizontally. Instead it is positioned at the right edge of the div.

My html code is this:

<div class="col-md-1" id="button_div"></div>

The button is dynamically created as follows:

closeButton = document.createElement("BUTTON");
var text = document.createTextNode("remove");
closeButton.className = "btn btn-danger";
closeButton.setAttribute("style", "margin: auto;");

closeButton.appendChild(text);                                      

$("#button_div").append(closeButton);

How can I center the button horizontally as well?


Solution

  • Seems to work fine. You don't need the margin:auto for the button.

    closeButton = document.createElement("BUTTON");
    var text = document.createTextNode("remove");
    closeButton.className = "btn btn-danger";
    /* closeButton.setAttribute("style", "margin: auto;"); */
    
    closeButton.appendChild(text);                                      
    
    $("#button_div").append(closeButton);
    #button_div {
      display: flex;
      align-items: center;
      justify-content: center;
      height: 200px;
      background-color: lightblue;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
    <div class="col-md-1" id="button_div"></div>