0

I want to Have a Text Box at the center. I tried with the code below. But it is not putting it at the center. Image of output can also be found below. Please help me by pointing errors in my code.

<html>

<head>

<style>

#form
{
    margin-top:40%;
    margin-left:40%;
}

</style>


</head>

<body>

<div id="form">

    <form method = "post" action = "test.htm" >
    UserName: <input type="text" name = "username" />   
    </form>
</div>

</body>

</html>

My output from the above code is:

enter image description here

abhinav
  • 527
  • 3
  • 11
  • 24

3 Answers3

2

you can use the below css code to make your text box in horizontally and vertically center.

#form {
    position: absolute;
    top: 50%;
    left: 50%;
    margin-top: -50px;
    margin-left: -50px;
    width: 100px;
    height: 100px;
}
Rahul J. Rane
  • 246
  • 1
  • 8
0

Here you go.

WORKING DEMO

The CSS Change:

div#form form {
    background: none repeat scroll 0 0 #808080;
    display: block;
    height: 100px;
    line-height: 100px;
    margin: 0 auto;
    text-align: center;
    vertical-align: middle;
    width: 100%;
}

Hope this helps.

Nitesh
  • 15,425
  • 4
  • 48
  • 60
  • I just want to do it with Margin property . Is that not possible. Why margin 50% not making it to the center?? – abhinav Jan 31 '14 at 10:04
  • But 50% of what?? You need to have a nested parent relative which can bound the margin to be 50% of the page. That would be altogether a different solution. - @abhinav – Nitesh Jan 31 '14 at 10:06
0

To get it vertically AND horizontally centered do this for the parent element:

position:relative;

Then the class/ID you want centered:

position:absolute;
top:0;left:0;bottom:0;right:0;
margin:auto;
/*and make sure this element has a width + height: example:!*/
width:100px;
height:100px;

Like this: Codepen

Albzi
  • 15,431
  • 6
  • 46
  • 63