2017-04-13 73 views
0

爲什麼輸入元素不是在將其顯示更改爲block後會自動佔用其容器寬度的100%?還有其他一些因素對此有影響嗎?謝謝。演示見下文:input element,display bock


一些解釋: 1.我註釋掉寬度:100%有意因爲塊級元素應該佔用它的容器寬度的100%。


#container { 
 
    width: 300px; 
 
    margin: auto; 
 
    background-color: red; 
 
} 
 

 
input[type="text"] { 
 
    display: block; 
 
    opacity:0.5; 
 
    /*width:100%;*/ 
 
}
<body> 
 
    <section> 
 
    <div id="container"> 
 
     <input type="text"> 
 
    </div> 
 
    </section> 
 
</body>

+0

註釋掉風格的寬度。 – Nitheesh

+0

給出寬度:輸入元素的100%並檢查。 –

+0

使用100%,這將取得父元素的全寬,所以你的輸入將是300px。提示:爲你的輸入字段添加一個類,不要使用「input [type =」text「]」來設置它們的樣式。 – divisionkiller

回答

0

我不是專家,但我敢肯定那是因爲你已經註釋掉寬度:100%。嘗試decommenting是那麼它應該工作

#container { 
 
    width: 300px; 
 
    margin: auto; 
 
    background-color: red; 
 
} 
 

 
input[type="text"] { 
 
    display: block; 
 
    opacity:0.5; 
 
    width:100%; 
 
}

0

改變了代碼檢查現在

#container { 
 
    width: 300px;margin: auto; 
 
    background-color: red; 
 
} 
 

 
input[type="text"] { 
 
    opacity:0.5; 
 
    width:100%; 
 
border-width:0; 
 
padding:0; 
 
}
<body> 
 
    <section> 
 
    <div id="container"> 
 
     <input type="text"> 
 
    </div> 
 
    </section> 
 
</body>

0

默認輸入元件具有border: 2pxpadding: 1px 0在谷歌瀏覽器

Box model of input element

當你在實際應用中的100%的寬度,輸入竟然出現了寬度比實際div的外面覆蓋輸入的它

寬度(集到div的寬度)+ border + padding> div的寬度

右邊有一個小小的白色區域,以防您在代碼中取消註釋width:100%。那個白色區域實際上是輸入。如果您設置邊界爲零,這真的夠解決的事情

#container { 
 
    width: 300px; 
 
    margin: auto; 
 
    background-color: red; 
 
} 
 

 
input[type="text"] { 
 
    display: block; 
 
    opacity: 0.5; 
 
    width: 100%; 
 
    border: 0 
 
}
<body> 
 
    <section> 
 
    <div id="container"> 
 
     <input type="text"> 
 
    </div> 
 
    </section> 
 
</body>
輸入

0

默認大小是20,因此,如果您的輸入自動它的大小是沒有定義的大小或CSS規則20. 最好的解決方案是增加寬度。如果你想成爲響應

#container 
{ 
    width: 300px; 
    margin: auto; 
    background-color: red; 
} 
input[type="text"] 
{ 
    display: block; 
    opacity:0.5; 
    width:100%; 
    -webkit-box-sizing: border-box; 
    -moz-box-sizing: border-box; 
    box-sizing: border-box; 
} 

最好是添加盒大小,以這樣的所有元素: 試試這個代碼

* 
{ 
    -webkit-box-sizing: border-box; 
    -moz-box-sizing: border-box; 
    box-sizing: border-box; 
} 
+0

20 _what_?我試圖與上面的例子:'em','ex','pc','ch','%','vw','rem','pt'。沒有什麼符合相同的尺寸。 PS:我沒有嘗試'px','vh'和打印單位,比如'cm','in',... – Werner

+0

您是否嘗試過** box-sizing **?此CSS指定元素應該在元素的總寬度和高度中包含填充和邊框。 –

+0

好的,我想出你所說的單位實際上是html-width('')。 – Werner