2016-03-21 77 views
1

爲什麼電子郵件和密碼寬度超出input-container寬度?CSS輸入元素寬度超出容器

form { 
 
    background: #ccc; 
 
    } 
 
    .input-container { 
 
    background: red; 
 
    width: 469px; 
 
    margin: 0 auto; 
 
    } 
 
    .usermail, 
 
    .userpword { 
 
    margin-top: 10px; 
 
    } 
 
    input, 
 
    button { 
 
    width: 100%; 
 
    border-radius: 6px; 
 
    border: 1px solid #cacece; 
 
    padding: 10px 12px; 
 
    font-size: 1em; 
 
    } 
 
    .username input { 
 
    width: 206px; 
 
    }
<form action='' method='post' id='signupform'> 
 
    <div class='input-container'> 
 
    <div class='username'> 
 
     <input type='text' name='fname' id='fname' placeholder='First Name'> 
 
     <input type='text' name='lname' id='lname' placeholder='Last Name'> 
 
    </div> 
 
    <div class='usermail'> 
 
     <input type='email' name='email' id='email' placeholder='Email'> 
 
    </div> 
 
    <div class='userpword'> 
 
     <input type='password' name='pword' id='pword' placeholder='Password'> 
 
    </div> 
 
    <button>Sign Up</button> 
 
    </div> 
 
</form>

+0

因爲你填充不計入寬度算,所以你的輸入是'100%+填充'寬。使用'box-sizing:border-box'來解決這個問題。此外,同樣適用於您的邊框。 – somethinghere

+2

[寬度爲100%的CSS輸入超出父級限制]的可能重複(http://stackoverflow.com/questions/16907518/css-input-with-width-100-goes-outside-parents-bound) – showdev

+0

^谷歌「CSS盒子模型」 –

回答

4

那是因爲你設置填充。它會將元素寬度的值與填充集相加。

爲了避免這種情況,建議添加屬性box-sizing: border-box

例子:

#element{ 
    box-sizing: border-box;} 

甚至更​​好:

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

具體而言,將其添加到'輸入,按鈕'CSS規則 – 4castle

+1

雖然'更好'是一個非常鬆散的定義,因爲許多人會爭辯說爲了整體性能而使用'*'通配符是_bad_。就個人而言,我不會使用'*',因爲它將整個盒子模型顛倒過來,現在認爲你知道的所有東西現在都有不同的作用,但這是個人偏好。 – somethinghere