2011-07-07 95 views
9

我已經在這裏看到了許多不同的答案,它們似乎都歸結爲父級div的樣式中的text-align:center。我試過了,它適用於標籤,但不是實際的輸入元素。表單輸入元素不居中

JSFiddle

這裏的基本代碼:

HTML

<div id="content"> 
    <div id="login_form"> 
    <h2>Log in to DOT Voting</h2> 
    <form> 
     <label for="username">Username</label> 
     <input type="text" name="username" value="" /> 
     <label for="password">Password</label> 
     <input type="password" name="password" value="" /> 
     <input type="submit" name="submit" value="Log In" /> 
    </div>  
</div> 

CSS

#login_form { 
    width:90%; 
    background-color: #bdd2ff; 
    border: 1px solid white; 
    margin: 50px auto 0; 
    padding: 1em; 
    -moz-border-radius: 10px; 
    -webkit-border-radius: 10px; 
    text-align: center; 
} 

input[type=text], input[type=password] { 
    text-align:center; 
    display: block; 
    margin: 0 0 1em 0; 
    width: 90%; 
    border: 1px solid #818181; 
    padding: 5px; 
} 

input[type=submit] , form a { 
    border: none; 
    margin-right: 1em; 
    padding: 6px; 
    text-decoration: none; 
    font-size: 12px; 
    -moz-border-radius: 4px; 
    -webkit-border-radius: 4px; 
    background: #cfdeff; 
    color: black; 
    box-shadow: 0 1px 0 white; 
    -moz-box-shadow: 0 1px 0 white; 
    -webkit-box-shadow: 0 1px 0 white; 
} 

input[type=submit]:hover, form a:hover { 
    background: #007cc2; 
    cursor: pointer; 
} 

的login_form DIV是居中在頁面上,表單標籤在div中居中,submit按鈕居中div。但文本輸入框不居中。我能做些什麼來強制他們居中? (我不在乎輸入框的內容是否居中;我只是希望框本身位於div的中心)

回答

18

添加

margin: auto; 

input[type=text], input[type=password]類。

此外請務必刪除text-align: center;屬性,因爲這會導致輸入中的文本居中。

JSFiddle

+0

謝謝,這工作。所有的答案都差不多;接受這個,因爲它是第一個。 – EmmyS

0

它基於90%輸入[type = text],輸入[type =密碼] css值。您可以使用固定寬度或液體佈局來定義寬度,並將其設置爲100%寬度並調整邊距。

2

修改margin聲明您input元素使用automargin-leftmargin-right

#login_form { 
    width:90%; 
    background-color: #bdd2ff; 
    border: 1px solid white; 
    margin: 50px auto 0; 
    padding: 1em; 
    -moz-border-radius: 10px; 
    -webkit-border-radius: 10px; 
    text-align: center; 
} 

input[type=text], input[type=password] { 
    text-align:center; 
    display: block; 
    margin: 0 auto 1em auto; 
    width: 90%; /*280px;*/ 
    border: 1px solid #818181; 
    /* -moz-border-radius: 1px; 
    -webkit-border-radius: 1px; */ 
    padding: 5px; 
} 

input[type=submit] , form a { 
    border: none; 
    margin-right: auto; 
    margin-left: auto; 
    padding: 6px; 
    text-decoration: none; 
    font-size: 12px; 
    -moz-border-radius: 4px; 
    -webkit-border-radius: 4px; 
    background: #cfdeff; 
    color: black; 
    box-shadow: 0 1px 0 white; 
    -moz-box-shadow: 0 1px 0 white; 
    -webkit-box-shadow: 0 1px 0 white; 
} 

input[type=submit]:hover, form a:hover { 
    background: #007cc2; 
    cursor: pointer; 
} 

Updated JS Fiddle

2

text-align在塊元素上不起作用。刪除display:blockinput[type=text], input[type=password]或將其更改爲display:inline-block。請注意,內聯塊不適用於< IE7。

或者因爲你對輸入聲明的寬度,你可以刪除text-align:center,並使用margin: 0 auto 1em auto;