Form - Cannot align a form to the center of webpage

Hi again,

Another issue im facing is I can’t seem to get my form to align dead smack middle of the webpage. Any ideas why im having such an issue. PS this is not a code challenge of any sort. Also, im really new so my code I’m sure will be far from nice and neat.

HTML

<style>
                                p {
                                    margin-top: 300px;
                                    
                                }
                                </style>
                                    <form action="/action_page.php" target="_blank">
                                        <label for="First Name">First Name</label>
                                        <input type="text" placeholder="Enter First Name">

                                        <label for="Email">Email Address</label>
                                        <input type="email" placeholder="Enter Email Address">

                                        <input type="submit" value="Submit" class="button">
                                    </form>    

CSS

form {
    margin: 60px;
    margin-top: 15px;
}

form label {
    display: block;
    margin: 10px 0px;
}

form input[type="text"],
input[type="email"] {
    display: block;
    padding: 10px 0;
    margin: 15px 0;
    border-radius: 5px;
    width: 25%;
}

form input[type="submit"] {
    display: block;
    padding: 10px 0;
    margin: 1px;
    border: 1px solid transparent;
    background: #3262ab;
    color: white;
    border-radius: 5px;
    width: 25%;
    cursor: pointer;
    transition: all 1s;

Hi, the simplest way would be that you wrap the form in a div and then set in the css:

div {
text-align: center;
 }

This should do the trick

The div moved the label only and not the text fields nor the submit button?

1 Like

Try applying the following property to the button and text element:

margin-left: auto;
margin-right:auto;

Which I think will center them in their containers.

You can do centering a bunch of different ways.

I would like to point out that you have to make sure you are looking at the right “thing”. The fact that the form element is transparent (it looks white because that is the body color) makes it harder to see where it actually is and how much space it is taking up.

Right now the form element is a block-level element and will take up all available horizontal space, centered or not. If you give the form some background color and a max-width you can see the element better. Now add margin: auto to center it.

form {
  max-width: 620px;
  margin: auto;
  padding: 10px;
  background: #2196f3;
}

Doing this may also reveal that the width you have set on the inputs are likely not really set in relation to the form but somewhat arbitrary.

Edit: you can also use something like this to better visualize the element boxes.

* {
  outline: 2px solid red;
}
1 Like