so I was building my navbar on my website, and I set every element that it has to position: fixed
, but I noticed that it wasn't really good looking and I would rather set it to position: static
, but here is my problem : when I change the position from fixed to static, the position on the screen of my element just changes.
Here is the CSS of one of my elements (a button) :
.discord img{
position: fixed;
display: block;
left: 3%;
bottom: 93%;
transform: scale(1);
transition: 0.3s;
filter: grayscale(1);
}
.discord img:hover{
position: fixed;
display: block;
left: 3%;
bottom: 93%;
transition: 0.3s;
transform: scale(1.1);
cursor: pointer;
filter: grayscale(0);
}
It acts just as if the left: 3%
and bottom: 93%
didn't matter anymore...
How can I fix this ?
CodePudding user response:
HTML elements are positioned static by default. No need to define that in your CSS, unless you are using a library/framework of some sorts that define the positioning on your element.
An element with position: fixed;
is positioned relative to the viewport, which means it always stays in the same place even if the page is scrolled.
This means that if you're setting left: 3%;
and bottom: 93%;
, the element will be positioned 97% to the left and 93% to the bottom (very close to the top) relative to the viewport - not its parent container, which in this case would be discord
.
So unless you want the element to be there while you're scrolling the page, don't use position:fixed;
. If you want your navbar to be set in place and stay there during scrolling, ONLY apply position: fixed;
to the navbar's parent - the full container containing all your img
-elements.
Codepen: https://codepen.io/sigurdmazanti/pen/wvpPJPz
Example snippet that has position:fixed;
on its parent container:
body {
height: 150vh;
background-color: blue;
}
nav.fixed {
width: 100%;
position: fixed;
}
nav.static {
width: 100%;
padding-top: 100px;
}
ul {
max-width: 50%;
margin: 0 auto;
list-style-type: none;
display: flex;
justify-content: space-between;
}
li {
background-color: white;
}
<body>
<nav >
<ul>
<li>fixed</li>
<li>fixed</li>
<li>fixed</li>
</ul>
</nav>
<nav >
<ul>
<li>static</li>
<li>static</li>
<li>static</li>
</ul>
</nav>
</body>