Search code examples
htmlcsscentering

How to center a button within a div?


I have a div that's width is 100%.

I'd like to center a button within it, how might I do this?

<div style="width:100%; height:100%; border: 1px solid">
  <button type="button">hello</button>
</div>


Solution

  • Updated Answer

    Updating because I noticed it's an active answer, however Flexbox would be the correct approach now.

    Live Demo

    Vertical and horizontal alignment.

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

    Just horizontal (as long as the main flex axis is horizontal which is default)

    #wrapper {
      display: flex;
      justify-content: center;
    }
    

    Original Answer using a fixed width and no flexbox

    If the original poster wants vertical and center alignment its quite easy for fixed width and height of the button, try the following

    Live Demo

    CSS

    button{
        height:20px; 
        width:100px; 
        margin: -20px -50px; 
        position:relative;
        top:50%; 
        left:50%;
    }
    

    for just horizontal alignment use either

    button{
        margin: 0 auto;
    }
    

    or

    div{
        text-align:center;
    }