Search code examples
csshtmlcenter

Center a div that contains a contact form


How do I center a contact form which is inside a div. I have tried margin:0 auto; and it didn't work.

<div id="new_div_3">
        <form class="contact_form" action="#" method="post" name="contact_form">
            <ul>
                <li>
                    <h2>Contact Us</h2>
                    <span class="required_notification">* Denotes Required Field</span>
                </li>
                <li>
                    <label for="name">Name:</label>
                    <input type="text"  placeholder="John Doe" required />
                </li>
                <li>
                    <label for="email">Email:</label>
                    <input type="email" name="email" placeholder="[email protected]" required />
                    <span class="form_hint">Proper format "[email protected]"</span>
                </li>
                <li>
                    <label for="website">Website:</label>
                    <input type="url" name="website" placeholder="http://johndoe.com" required pattern="(http|https)://.+"/>
                    <span class="form_hint">Proper format "http://someaddress.com"</span>
                </li>
                <li>
                    <label for="message">Message:</label>
                    <textarea name="message" cols="40" rows="6" required ></textarea>
                </li>
                <li>
                    <button class="submit" type="submit">Submit Form</button>
                </li>
            </ul>
        </form>
    </div>

I have tried using various methods and none of them seem to work to center the div. I even tried centering the contact form itself and it just moved the input fields to the center of the contact form, rather than the div.


Solution

  • In order to get margin: 0 auto; work you need to set width.

    #new_div_3 {
        width: 500px;
        margin: 0 auto;
    }
    

    Check the fiddle: http://jsfiddle.net/9cMAC/