2011-04-25 70 views
2

jsFiddle如何使用CSS將此文本框居中?

如何將文本框居中在範圍內(#inner_span)?我嘗試使用margin-left:auto; margin-right:auto;但它似乎並不奏效。

CSS

div.user_form { 
    background: #EEE; 
    padding:15px; 
    margin-bottom: 10px; 
    border: #CCC solid 1px; 
    -moz-border-radius: 15px; 
} 

.user_input_class { 
    text-align: center; 
} 

HTML

<div class="user_form"> 
    <span class="user_form_inner_span" id="inner_span"> 
     <form> 
      <span class="user_input_span"> 
       <input type="text" name="user_input" size="70" class="user_input_class"> 
      </span> 
      <input type="checkbox" value="Private" name="private"> Option 
      <center> 
       <input type="submit" value="Add" class="add_user_button" 
      </center> 
     </form> 
    </span> 
</div> 

回答

2

span#inner_span實際上應該是一個div,因爲你不能嵌套塊級別form在內聯元素內,但是這僅僅是用於信息,對第是問題;)

它實際上是跨度user_input_span輸入是你需要在中心 - 跨度是內聯元素,所以他們不會接受寬度,這就是爲什麼他們不會使用中心margin: 0 auto; - 你可以轉換元素到inline-blocks具有寬度然後應該這樣做,或者也可以簡單使用與文本對齊的內聯元件

  1. form元件中心文本
  2. 重置文本對齊到左在實際輸入元件(或者如果這是您的偏好,請將其置於中心位置)

.user_form { 
    background: #EEE; 
    padding:15px; 
    margin-bottom: 10px; 
    border: #CCC solid 1px; 
    -moz-border-radius: 15px; 
} 

.user_form form { 
/* center all the inputs in a form */ 
text-align: center; 

/* how to center the whole form*/ 
width: 600px; 
margin: 0 auto; 
background: #ffe; 
} 

.user_form span { 
/* reset text-alignment in the inputs */ 
text-align: left; 
} 
0

保證金自動將工作,如果父母有一定的寬度,以便嘗試應用一些寬度user_input_span等;

.user_input_span{ 
width: 100%; /* this can be as per your need or form width */ 
} 
.user_input_class { 
    text-align: center; 
    margin-left: auto; 
margin-right: auto; 
} 

編輯:

好吧,這是你的工作代碼

.user_input_span{ 
width: 300px; /* this can be as per your need or form width */ 
display:inline-block; 
} 
.user_input_class { 
    text-align: center; 
    margin:0 auto ; 
    width:80px; 
    display:block; 
} 

更新Fiddle

+0

謝謝您的回答,似乎並沒有工作,雖然? http://jsfiddle.net/5uGRq/5/ – ben 2011-04-25 07:23:14

+0

請參閱編輯部分 – 2011-04-25 08:04:47