[英]How to position: fixed div relate to the its position: relative parent?
[英]child div with position fixed should have same width as parent div with position relative
我想在滾動后修復一個 div 的 position。 但是當我將 position 更改為fixed
div 時,它會從它的容器中取出。 class fixed
的 div 應該與 class relative
的 div 一樣寬。 父 div 的寬度是動態的。 只有最大寬度是已知的。 不應該使用 position 粘性。
我正在嘗試實現以下目標:單擊按鈕時,會打開一個表單。 表格應該是固定的。
已經有一些關於這個主題的主題。 但是,這些解決方案對我不起作用。 也可以用 JS(但不用 JQuery)來解決。
以下解決方案對我不起作用:
.relative { position: relative; background-color: red; max-width: 1200px; height: 150vh; }.absolute { position: absolute; background-color: blue; top: 0; left: 0; right: 0; bottom: 0; width: inherit; }.fixed{ position: fixed; background-color: green; height: 50px; width: inherit; z-index: 5; }
<div class="relative"> <div class="absolute"> <form class="fixed"></form> </div> </div>
您需要在兩個子元素上繼承您的最大寬度,並在最后一個應用寬度:100%。 並將您的粘性 class 應用到固定 div。
.relative { position: relative; background-color: red; max-width: 1200px; height: 150vh; }.absolute { position: absolute; background-color: blue; top: 0; left: 0; right: 0; bottom: 0; width: inherit; max-width: inherit; }.sticky { position: fixed; background-color: green; height: 50px; width: inherit; z-index: 5; max-width: inherit; width: 100%; }
<div class="relative"> <div class="absolute"> <form class="sticky"></form> </div> </div>
了解固定:( 完整博客在這里)
“與絕對不同,固定 position 本身不會從其最近的相對父級。相反,固定位置本身相對於視口。視口將始終保持固定,這就是為什么你會得到你所做的效果。
話雖如此,只要您“繼承”任何寬度,它將與 viewport 相關。 因此,當我們嘗試將目標元素的寬度設置為其父元素的寬度時,這對我們沒有好處”
Css 固定 position 玩起來有點棘手,也許你應該考慮使用position:sticky 。 它保持相對於其父元素。
嘗試這個:
* { margin: 0%; padding: 0%; box-sizing: border-box; }.relative { background-color: red; width: 50%; height: 350vh; }.absolute { background-color: blue; position: sticky; top: 50%; margin-left: 50%; transform: translate(-50%, -50%); width: 50%; height: 25vh; display: flex; justify-content: center; align-items: center; }.fixed { background-color: green; height: 50%; width: 80%; }
<div class="relative"> <div class="absolute"> <form class="fixed"></form> </div> </div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.