Search code examples
htmlcsscentertext-alignmenttext-align

How can I horizontally center a button element in a div element?


I don't want to add CSS to my div element (e.g. <div style="text-align: center;">).

I only want to add CSS code to the button element.

<div>
  <button>Button</button>
</div>

How can I center the button horizontally in this case?


Solution

  • You can set margin-left/right to auto, which will be applied when the button is displayed as block.

    button {
        margin: 0 auto;
        display: block;
    }
    

    button {
      margin: 0 auto;
      display: block;
    }
    <div>
      <button>Button</button>
    </div>