2014-01-31 20 views
0

我想有一个文本框在中心。我尝试了下面的代码。但它并没有把它放在中心位置。输出的图像也可以在下面找到。请通过在我的代码中指出错误来帮助我。如何在中心使用保证金属性在中心Div元素

<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> 

我从上面的代码输出为:

enter image description here

+0

设置'margin:0 auto;' –

+0

检查下面的答案。 - @Abhinav – Nitesh

回答

0

在这里你去。

WORKING DEMO

CSS的变化:

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%; 
} 

希望这有助于。

+0

是的。回答编辑。 - @CTravel – Nitesh

+0

我只想用Margin属性来做。这是不可能的。为什么利润率50%没有达到中心? – abhinav

+0

但50%的是什么?您需要有一个嵌套的父亲关系,它可以将页边距限制为页面的50%。这完全是一个不同的解决方案。 - @abhinav – Nitesh

0

为了得到它垂直和水平居中做到这一点父元素:

position:relative; 

那么类/ ID你想中心:

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; 

像这样:Codepen

2

你可以使用下面的CSS代码使您的文本框在水平和垂直中心。

#form { 
    position: absolute; 
    top: 50%; 
    left: 50%; 
    margin-top: -50px; 
    margin-left: -50px; 
    width: 100px; 
    height: 100px; 
}