[英]How can I make the width of an element a percentage of its parent while the using position: fixed property?
這里我有以下結構: parent
> container
> main-section
> post_creation
> h3
和一個input
字段。
我需要將h3
元素固定在屏幕上,這樣當我上下滾動時,h3 元素仍然可見。 同時,我需要h3
元素的寬度為post_creation
的 98%。 但是,發生的情況是寬度設置為頁面寬度的 98%。
.parent { height: 200vh; width: 400px; } h3 { position: fixed; width: 98%; }
<body> <div class="parent"> <div class="container"> <div class="left-section"></div> <div class="main-section"> <div class="post_creation"> <h3>home</h3> <input type="text" placeholder="Aliens thinking of what?"> </div> </div> <div class="right-section"></div> </div> </div> </body>
當一個元素有一個fixed
的 position 時,它被從正常的 html 流中取出,因此該元素對其周圍的元素一無所知。 因此,您只能將其寬度設置為周圍window
的百分比。
您可以使用 javascript 來獲得您想要的。 只需使用 class post_creation
元素width
的 98%(在本例中為400px
),並將h3
設置為該寬度(在本例中392px
)。
var postCreationEl = document.querySelector('.post_creation'); var h3Element = document.querySelector('h3'); var style = window.getComputedStyle(postCreationEl, null); var width = style.width; width = parseInt(width.replace("px", "")); var widthForH3 = Math.floor(width * (98 / 100)); h3Element.style.width = widthForH3.toString() + "px";
.parent { height: 200vh; width: 400px; background-color:blue; } h3 { position: fixed; background-color:red; }
<div class="parent"> <div class="container"> <div class="left-section"></div> <div class="main-section"> <div class="post_creation"> <h3>home</h3> <input type="text" placeholder="Aliens thinking of what?"> </div> </div> <div class="right-section"></div> </div> </div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.