[英]How to force position absolute with 100% width to fit into parent div with padding?
我有 2 個 div,一個外部 div,它是一個父 div 和一個子 div。 外部 div 是位置相對,左右邊距為 20px,而子項是絕對位置,寬度為 100%。 如何強制絕對位置的孩子在父級內,即尊重內邊距 20px(在父級內和 20px 內邊距內)
我在這里做了這個例子: http : //www.bootply.com/nyGZzTVY8v
我已經閱讀了 box-sizing 但我仍然不明白如何正確實現它。 嘗試將它放在 box1 類上,但沒有任何反應,嘗試將其放在 box2 類上,也沒有任何反應。
提前致謝。
附加說明:它必須是響應式的,即我不知道父 div 的大小,因此 100% 為子 div。
只需設置left: 20px;
right: 20px;
並移除width: 100%
.box2 {
position: absolute;
padding: 50px 0;
color: #000;
background: #fff;
left: 20px;
right: 20px;
border: solid thin #06F;
}
或添加left: 20px;
和calc 函數width: calc( 100% - 40px )
.box2 {
position: absolute;
width: calc( 100% - 40px );
padding: 50px 0;
color: #000;
background: #fff;
left: 20px;
border: solid thin #06F;
}
如果必須響應,您可以添加填充作為邊距,然后使用 calc 作為寬度:
.box2 {
position: absolute;
width: calc(100% - 40px);
left: 0px;
padding: 50px 0;
margin: 0 20px;
colour: #000;
background: #fff;
border: solid thin #06F;
}
一旦你使用絕對位置,div 就不會在它的父 div 中。相反,你可以使用相對位置並給它width:inherit
這將繼承父 div 的寬度
這工作完美,試試看。 父 div 應該有一個相對位置,子 div 可以有你想要的絕對位置。
.box1 {
width: 50%;
margin: 10px;
position:relative;
}
.box2 {
display: block;
position: absolute;
width: 100%;
}
我最近遇到了這個問題,並通過設置子容器的左右解決問題找到了解決方案。
如果您希望子容器具有相同的父填充,例如 padding: 0 10px ie left & right。 然后我們需要將子容器的左右設置為與父填充相同的值。
.box1 {
position: relative;
padding: 0 10px;
}
.box2 {
position: absolute;
left: 10px;
right: 10px;
}
要查看代碼筆,請單擊此處
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.