My Problem is, that somehow, my header, or more specific the element with the class test
, is not 100% centered, but the header-image
is. I've checked the left position and width with js.
const element = document.querySelector(".header-image");
const observer = new IntersectionObserver(
([e]) =>
headerSticky(e),
{ threshold: [1] }
);
observer.observe(element);
function headerSticky(element) {
element.target.classList.toggle("is-sticky", element.intersectionRatio < 1);
document.querySelector(".header").classList.toggle("image-is-sticky", element.intersectionRatio < 1);
}
* {
padding: 0;
margin: 0;
font-family: Arial, Helvetica, sans-serif;
box-sizing: border-box;
}
:root {
}
body, html {
height: 200vh;
width: 100%;
}
.header-image {
position: sticky;
top: -1px;
left: 50%;
transform: translate(-50%, 0);
margin-top: 15%;
height: 350px;
aspect-ratio: 1/1;
background: red;
z-index: 1001;
transition: .5s;
}
.header-image.is-sticky {
height: 80px;
}
.header {
position: fixed;
display: flex;
justify-content: center;
top: 0;
width: 100%;
height: 80px;
background: hsla(0, 0%, 0%, .3);
z-index: 1000;
color: white;
}
nav {
display: flex;
align-items: center;
height: 100%;
background: yellow;
gap: 0;
transition: .2s;
}
.image-is-sticky nav {
/* gap: 80px; */
}
.nav-menu {
height: 100%;
display: flex;
align-items: center;
background: blue;
}
.nav-link {
color: black;
margin: 0 1rem;
background: lime;
}
<div class="header-image"></div>
<header class="header">
<nav>
<ul class="nav-menu">
<a class="nav-link">Home</a>
<a class="nav-link">News</a>
<a class="nav-link">Saison</a>
</ul>
<div class="test" style="height: 80px; aspect-ratio: 1/1; background: cyan;">
</div>
<ul class="nav-menu">
<a class="nav-link">Tickets</a>
<a class="nav-link">Team</a>
<a class="nav-link">Kontakt</a>
</ul>
</nav>
</header>
I've found the issue. The issue was that the menu's had different widths. So I've just put on the .nav-link
a min width
.nav-link {
display: flex;
justify-content: center;
color: black;
margin: 0 1rem;
background: lime;
/* new */
min-width: 75px;
}
But you could also fix it, when you set somehow via the flexbox a same width for every child.