Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does margin:0 auto; not work on this input button?

Tags:

html

css

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?

like image 616
AlecR Avatar asked Oct 10 '15 23:10

AlecR


People also ask

Why margin 0 Auto does not work?

First things first, each of the elements above are blocks and have set margin: 0 auto, but it does not work since blocks have width equal to 100% by default (the first example). The block covers the whole page and therefore cannot be centered.

Why margin-right is not working?

You cannot see the effect of margin-right because the 'width' property of div causes the margin of div to have more than 10px distance from the right wall of the body. Consequently, it causes the margin-right property not to have any visual effect.

How do you use auto margin?

The auto Value You can set the margin property to auto to horizontally center the element within its container. The element will then take up the specified width, and the remaining space will be split equally between the left and right margins.


1 Answers

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 ;)

like image 59
Tempestas Ludi Avatar answered Sep 28 '22 10:09

Tempestas Ludi