14
votes

I'm trying to center an input button within a form but the usual margin: 0 auto; isn't doing anything. Here's how my HTML is set up:

<body>
<div class="container">
    <div class="contact-div">
        <form id="contact-form">
            <div class="input-field">
                <input type="button" value="Submit" class="submit-button" />
            </div>
        </form>
    </div>
</div>
</body>

and the CSS:

body {
    padding:0;
    margin:0;
    width:100%;
    font-family: Century Gothic,sans-serif;
}

.container {
    width:100%;
}

#contact-div {
    height:100vh;
    width:100%;
    background: url("images/contactpic3.jpg") no-repeat center fixed; 
    background-size: cover;
}

.input-field{
    width:60%;
    margin:0 auto;
}

.submit-button {
    height:40px;
    width:200px;
    margin:auto;
    border:2px black solid;
    border-radius:10px;
    font-size:1.5em;
    text-align:center;

}

Here is also a JSFiddle with the problem (https://jsfiddle.net/wge66p83/). As you can see by the red background color I added, the submit button isn't centering and is just sticking to the left edge of the input-field. How can I get this input to center in my div?

3

3 Answers

45
votes

For the margin: auto trick to work, the element must be a block. So, add display: block; to the button css and you'll be fine ;)

3
votes

all input elements are inline by default, for applying margin you must use Display: block;

2
votes

You can add a text-align: center to the input-field, which will automatically horizontally center anything within that element.

.input-field{
    width:60%;
    margin:0 auto;
    background-color:red;
    text-align:center;
}