標籤:type pre 尺寸 沒有 css 瀏覽器 logs char meta
先上結論:
子項目沒有設定定位,其尺寸設定百分比參照的對象是 該子項目的父級元素;
子項目絕對位置後,其尺寸設定為百分比參考的對象是 該子項目設定了定位(這裡的定位包括絕對位置,相對定位和固定定位)的祖先元素(一層一層往上找,直到找到定位的祖先元素停止)。若沒有找到目標,則參照的是瀏覽器視窗。
下面是測試代碼
子項目不設定定位,父元素也不設定定位
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Document</title> <style> .father{ width: 300px; height: 300px; background-color: yellow; } .son{ width: 200px; height: 200px; background-color: blue; } .grandson{ width: 100%; height: 100px; background-color: pink; } </style></head><body> <div class="father"> <div class="son"> <div class="grandson"> </div> </div> </div></body></html>
效果如下:
可以看到子項目尺寸參照的是父級元素。
在上面代碼的基礎上,給黃色盒子設定定位:
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Document</title> <style> .father{ width: 300px; height: 300px; background-color: yellow; position: relative; } .son{ width: 200px; height: 200px; background-color: blue; } .grandson{ width: 100%; height: 100px; background-color: pink; } </style></head><body> <div class="father"> <div class="son"> <div class="grandson"> </div> </div> </div></body></html>
效果如下:
看到和上面結果一樣,說明子項目沒有設定定位,不會理睬設定了定位的祖先元素。
接著在上面的基礎上,給粉色的盒子設定絕對位置:
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Document</title> <style> .father{ width: 300px; height: 300px; background-color: yellow; position: relative; } .son{ width: 200px; height: 200px; background-color: blue; } .grandson{ width: 100%; height: 100px; background-color: pink; position: absolute; } </style></head><body> <div class="father"> <div class="son"> <div class="grandson"> </div> </div> </div></body></html>
效果
看到,子項目(粉色盒子)的寬度和設定了定位的祖先元素(黃色盒子)的寬度一樣。
接著,將祖先元素的定位去掉。代碼如下:
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Document</title> <style> .father{ width: 300px; height: 300px; background-color: yellow; /*position: relative; */ //我是去掉的定位 } .son{ width: 200px; height: 200px; background-color: blue; } .grandson{ width: 100%; height: 100px; background-color: pink; position: absolute; } </style></head><body> <div class="father"> <div class="son"> <div class="grandson"> </div> </div> </div></body></html>
效果如下:
子項目(粉色盒子)的寬度為瀏覽器的寬度(因為其祖先元素沒有定位)。
上述結論成立。
【CSS】定位之下尺寸百分比參考對象