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

后端 未结 3 1760
隐瞒了意图╮
隐瞒了意图╮ 2020-12-24 01:09

I don\'t want to add CSS to my div element (e.g.

).

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

<
相关标签:
3条回答
  • 2020-12-24 01:49
    button {
        margin:0 auto;
        display:block;
    }
    

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

    0 讨论(0)
  • 2020-12-24 01:54

    Others have already mentioned the margin: 0 auto; method, but if you wanted an explanation, the browser splits up the available space in whatever container your element is in.

    Also important to point out is you'll probably need to give your element a width, too, for this to work correctly.

    So, overall:

    button {
        display:inline-block; //Typically a button wouldn't need its own line        
        margin:0 auto;
        width: 200px; //or whatever
    }
    
    0 讨论(0)
  • 2020-12-24 02:00

    You need display: block; margin: auto; on the <button>. jsFiddle

    0 讨论(0)
提交回复
热议问题