David
David

Reputation: 1

Vertically and Horizontally Aligning in CSS

I'm having trouble getting my form to align both vertically and horizontally.

I don't mind if this doesn't support IE--I plan on implementing an IE detection script to tell the user to use a different browser--but support for Firefox and Chrome is a must.

Here is what I currently have:

HTML

<!DOCTYPE html>
<head>
    <link rel="stylesheet" type="text/css" href="global.css">
    <link rel="stylesheet" type="text/css" href="index.css">
</head>
<body>
    <div id="wrapper">
        <div id="logo_div">
            <img src="../images/logo.png" id="logo">
        </div>

        <div id="login">
            <form name="searchform" action="checklogin.php" method="post" id="login_form">
            <br>
                User Name : <input type="text" name="myusername" size="16" /><br>
                Password : <input type="password" name="mypassword" /><br>
                <input type="submit" value="Login" /><br>
            </form>
        </div>
    </div>
    </div>
</body>
</html>

Global CSS

#wrapper {
    position: relative;
    max-width: 1024px;
    height: 1000px;
    margin-left: auto;
    margin-right: auto;
}
#logo_div {
    position: relative;
    margin-left: auto;
    margin-right: auto;
}

#logo {
    display: block;
    position: relative;
    margin-left: auto;
    margin-right: auto;
}

Index CSS

#login {
    position: relative;
    margin-left: auto;
    margin-right: auto;
}
#login_form {
    position: relative;
    margin-left: auto;
    margin-right: auto;
}

Any help is appreciated. Thanks

Upvotes: 0

Views: 258

Answers (2)

Osho
Osho

Reputation: 123

Do you want something like this?

try this css

#login{
    position:absolute;
    left:50%;
    top:50%;

    margin-left:-120px;
    margin-top:-60px;

    border:1px solid #ccc;
    width:240px;
    height:120px;
}

If you want a form centered vertically and horizontally, you can use css attribute position:absolute; and then use left:50%; top:50% to align the top-left corner of div to center of browser. But your Div will not look centered by this. because it is centered to window by its top left corner. I just used negative margin with half of width and height of div to center it properly.

Hope this is what you are looking for.

Thanks Bojangles, for suggestion !

Upvotes: 3

Right now your #login div is using 100% of the page width, you need to set a smaller width so it can be centered correctly. And you can center it vertically by setting top to 50% minus div height / 2.

Like this

#login
{
    position: relative;
    margin-left: auto;
    margin-right: auto;
    width: 300px;
    top: 50%;
    margin-top:-50px;
}

Upvotes: 0

Related Questions