簡體   English   中英

讓孩子用填充填充父母的100%

[英]Make child fill 100% of parent with padding

我正在嘗試使用父母寬度和高度的100%(包括填充)來制作子div 無論我嘗試什么,都行不通。 我試圖添加box-sizing = border-box但是沒有任何改變。 我還嘗試使用*將框大小添加到所有元素,但也沒有任何改變。 這是我的代碼:

 html { font-size: 16px; } .parent { font-size: 1rem; width: 10em; height: 10em; padding: 5em; background-color: #f0f0f0; } .child { background-color: #ccc; width: 100%; height: 100%; /* --= 100% should include padding =-- box-sizing: border-box; <-- this didn't change anything... */ } 
 <div class="parent"> <div class="child"></div> </div> 

如果相對於父級絕對放置,則子級將放置在其父級填充的外部。 使用position:absolute像這樣:

.parent {
  position: relative;
  padding: 2em;
}

.child {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

示范:

 html { font-size: 12px; } body { margin: 1em; } .parent { position: relative; font-size: 1.2em; width: 10em; padding: 2em; margin:1em 0 0; background-color: blue; border: 5px solid red; } .child { position: relative; background-color: lightgreen; } .background { position: absolute; top: 0; left: 0; width: 100%; height: 100%; } p { margin: 0; } .red { color: red; } .blue { color: blue; } .green { color: green; } 
 <p>Parent Border: <span class="red">Red</span></p> <p>Parent Background: <span class="blue">Blue</span> (not visible)</p> <p>Child Background: <span class="green">Green</span></p> <div class="parent"> <div class="child background"></div> <div class="child">This text to indicate parent's padding</div> </div> 

您的代碼的工作示例:

 html { font-size: 16px; } .parent { position: relative; /* ADDED */ font-size: 1rem; width: 10em; height: 10em; padding: 5em; background-color: #f0f0f0; } .child { position: absolute; /* ADDED */ left: 0; /* ADDED */ top :0; /* ADDED */ background-color: #ccc; width: 100%; height: 100%; } 
 <div class="parent"> <div class="child"></div> </div> 


一個解釋:

絕對定位模型中,框相對於其包含的block明顯偏移。

W3絕對定位

如果position屬性是static或relative ,則包含塊由最接近祖先元素的內容框的邊緣形成,該元素是一個塊容器...

如果position屬性是absolute ,則包含塊的位置由最接近祖先元素的填充框的邊緣形成,該邊緣的位置值不是靜態值(固定值,絕對值,相對值或粘性值)。

識別包含塊@ moz

重點和粗體由我補充。

進一步參考: 箱型

在不更改父級元素的情況下,唯一的方法就是覆蓋父級元素的填充。 為此,您需要將widthheight設置為calc(100% + 10em) 您還需要取反左側和頂部填充以正確定位元素。 設置孩子的position: relative ,並將lefttop設置為-5em

 html { font-size: 16px; } .parent { font-size: 1rem; width: 10em; height: 10em; padding: 5em; background-color: #f0f0f0; } .child { background-color: #ccc; width: calc(100% + 10em); height: calc(100% + 10em); position: relative; left: -5em; top: -5em; } 
 <div class="parent"> <div class="child"></div> </div> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM