Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
589 views
in Technique[技术] by (71.8m points)

html - CSS : center form in page horizontally and vertically

How can i center the form called form_login horizontally and vertically in my page ?

Here is the HTML I'm using right now:

<body>
    <form id="form_login">
        <p>
            <input type="text" id="username" placeholder="username" />
        </p>
        <p>
            <input type="password" id="password" placeholder="password" />
        </p>
        <p>
            <input type="text" id="server" placeholder="server" />
        </p>
        <p>
            <button id="submitbutton" type="button">Se connecter</button>
        </p>
    </form>
</body>

I have tried to do the following css but my form is never centered :

#form_login {
    left: 50%;
    top: 50%;
    margin-left: -25%;
    position: absolute;
    margin-top: -25%;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

you can use display:flex to do this : http://codepen.io/anon/pen/yCKuz

html,body {
  height:100%;
  width:100%;
  margin:0;
}
body {
  display:flex;
}
form {
  margin:auto;/* nice thing of auto margin if display:flex; it center both horizontal and vertical :) */
}

or display:table http://codepen.io/anon/pen/LACnF/

body, html {   
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
    display:table;
}
body {
    display:table-cell;
    vertical-align:middle;
}
form {
    display:table;/* shrinks to fit content */
    margin:auto;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...