Reputation: 27
I want to center a Div element in CSS. I have tried everything I found. Nothing seems to work? I've checked my CSS with W3C's validator. No errors. I am clueless. This is my latest attempt.
body {
background: url(loginbg.jpg) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
input[type="text"], input[type="password"] {
float: left;
width: 230px;
padding: 15px 5px 5px 5px;
margin-top: 5px;
margin-left: 3px;
border: 1px solid #999999;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
border-radius: 5px;
}
#submit_img, #sumbit_button {
cursor: pointer;
margin:0 auto;
}
#loginarea {
margin:0 auto;
}
mY HTMl code:
<head>
<link rel="stylesheet" type"text/css" href="login.css">
<title>
Login
</title>
</head>
<body>
<div id="loginarea" class="loginarea">
<div id="username_box">
<input type="text" id="username" value="Username">
</div> <div id="password_box">
<br><br><br><br>
<input type="password" id="password" value="Password">
</div>
<br><br><bR>
<button id="sumbit_button" style="border: 0; background: transparent;">
<img src="loginbutton.png" width="150" height: "50" id="sumbit_img">
</button>
<br>
</div>
<div id="footer" class="footer">
Copyright 2013 company name| CraftManager 1.2 | Credits
</div>
</body>
</html>
Is it the footer blocking the centering?
Current Status:
I have set a width on the div , and "centered" the margins. It makes a difference, though it isn't truly centered.
Upvotes: 1
Views: 277
Reputation: 731
It looks like the loginarea div is not closed. Please double check that.
Upvotes: 0
Reputation: 33339
By default a <div>
element fills 100% of parent element's width. If you want to center it, then the first thing you have to do is make it less than 100% wide.
So set a width on the div, 200px or something, and then you can set margin-left: auto;
and margin-right: auto;
#loginarea {
width: 200px;
margin: 0 auto; /* top/bottom: 0 margin. left/right: auto margin */
}
Upvotes: 3
Reputation: 21191
auto
margins only work when the element to center has a "known" size. So, if you want #loginarea
to be centered, you need to give it a width:
#loginarea {
width:30em; /* can be any relative or fixed size, like 200px or 30% */
margin: 0 auto;
}
Example: jsFiddle: http://jsfiddle.net/XBCVc/1/
Upvotes: 0
Reputation: 4746
try set
margin-left: auto ;
margin-right: auto ;
for more details check here
Upvotes: 0
Reputation: 58
I've done this before, code isn't handy so I googled it. http://www.dzone.com/snippets/dead-centre-div may help.
I don't know why it won't let you do so by doing 50% from the left with css and 50% from the top.
Are you interested in centering it both vertically and horizontally?
that's what I was interested in, and my own results and success rate even depended on the size of the div.
Upvotes: 0