I have a main div containing two divs. One takes up 276px, the other takes up the rest of the space (flex: 1). The second div has a header that should scroll along with the page. The problem is that now it takes up 100% of the width of the entire site, but it should only take up the length of the second block. I was able to set the required width when I set the main div to a fixed width and the header to max-width: inherit. But the problem is that the header has become non-adaptive and does not shrink when the screen gets smaller. How can this be implemented so that it is adaptive?
.parent-div {
width: 100%;
display: flex;
gap: 20px;
}
.child-div-1 {
width: 276px;
}
.child-div-2 {
flex: 1;
}
.fixed-header {
position: fixed;
top: 10px;
width: 100%;
display: flex;
justify-content: space-between;
align-items: center;
padding: 8px 16px;
height: 56px;
border-radius: 8px;
background: linear-gradient( 102deg, #ff6662 -0.12%, #3268f4 117.01%, #193fb2 138.81%);
}
<div class="parent-div">
<div class="child-div-1"></div>
<div class="child-div-2">
<div class="fixed-header"></div>
</div>
</div>
I have additional functionality where this header appears when scrolling when the banner is not visible:
window.addEventListener("scroll", function () {
const banner = document.querySelector(".banner");
const header = document.querySelector(".fixed-header");
if (banner) {
let isBannerVisible = banner.getBoundingClientRect().bottom >= 0;
if (isBannerVisible) {
header.classList.remove("show");
} else {
header.classList.add("show");
}
}
});
2
Answers
Don’t use
position: fixed
as this is related to the viewport not the parent.Use
position: sticky
instead.I have tried to modify your code as per your requirement. I hope this helps: