2015-11-24 77 views
0

從下面的代碼,爲什麼內部容器容器溢出?

.shoppingform { 
 
    width: 400px; 
 
    height: 800px; 
 
    background: #7CB9E8; 
 
    /* url(some img)*/ 
 
    padding-left: 15px; 
 
    padding-top: 10px; 
 
    color: white; 
 
    font-size: 12px; 
 
    font-weight: bold; 
 
    border-radius: 5px; 
 
} 
 
.customercardtype { 
 
    border: 1px solid white; 
 
    color: black; 
 
    font-weight: normal; 
 
    padding: 10px 2px 5px 5px; 
 
    background: #B284BE; 
 
    width: 90%; 
 
    border-radius: 5px; 
 
    position: relative; 
 
    height: 8%; 
 
    margin-top: 5px; 
 
} 
 
.customercardtype .formlabel { 
 
    display: block; 
 
    height: 20% 
 
} 
 
.customercardtype .cardtypecontainer { 
 
    position: absolute; 
 
    width: 100%; /* Any problem here? */ 
 
    top: 40%; 
 
    height: 50%; 
 
    border: 1px solid red; 
 
}
<form class="shoppingform" action="someaction.php" method="get" enctype="multipart/form-data"> 
 
    Step3: Card details 
 
    <div class="customercardtype"> 
 
    <label class="formlabel">Cardtype:</label> 
 
    <div class="cardtypecontainer"> 
 

 
    </div> 
 
    </div> 
 
</form>

我想明白了,

爲什麼內div容器溢出?

enter image description here

回答

3

這是因爲元件的寬度實際上是寬度+左填充+右填充+左邊界+右邊界。

由於您的寬度是100%,並且額外的這會將其推到100%以上,使其溢出其父項。

如果您使用框大小:邊框,將解決此問題。

這是一個快速總結,更多深入信息在這裏:https://css-tricks.com/box-sizing

1

溢出的原因是因爲position absolute視覺上講,定位網站的正常流動外的元素。如果您正確使用它,這是有意和強大的。然而在你的情況下,cardtypecontainer的父容器沒有控制絕對定位的元素,因此溢出了它的容器。

然後,我將cardtypecontainer更改爲具有relative的位置,它將按照您的預期工作,因爲relative位置不會更改元素的預期佈局。對於你的情況,這意味着,cardtypecontainer將停留在其父容器的範圍內。

.shoppingform { 
 
    width: 400px; 
 
    height: 800px; 
 
    background: #7CB9E8; 
 
    /* url(some img)*/ 
 
    padding-left: 15px; 
 
    padding-top: 10px; 
 
    color: white; 
 
    font-size: 12px; 
 
    font-weight: bold; 
 
    border-radius: 5px; 
 
} 
 
.customercardtype { 
 
    border: 1px solid white; 
 
    color: black; 
 
    font-weight: normal; 
 
    padding: 10px 2px 5px 5px; 
 
    background: #B284BE; 
 
    width: 90%; 
 
    border-radius: 5px; 
 
    position: relative; 
 
    height: 8%; 
 
    margin-top: 5px; 
 
} 
 
.customercardtype .formlabel { 
 
    display: block; 
 
    height: 20% 
 
} 
 
.customercardtype .cardtypecontainer { 
 
    position: relative; 
 
    margin-top: 10px; 
 
    width: 100%; 
 
    height: 50%; 
 
    border: 1px solid red; 
 
}
<form class="shoppingform" action="someaction.php" method="get" enctype="multipart/form-data"> 
 
    Step3: Card details 
 
    <div class="customercardtype"> 
 
    <label class="formlabel">Cardtype:</label> 
 
    <div class="cardtypecontainer"> 
 

 
    </div> 
 
    </div> 
 
</form>