I have a div that contains three SVG files that are layered on top of each other and supposed to be located on the center of the page. When the user scrolls down the page I want the SVG files to stick to the top and remain there.
As you can see in the CSS I have tried using position: sticky; and top:0; However I believe this is causing a “BUG” since the SVG files are layered using position: relative;. The graphic is now uncentered and it does not remain stuck to the top of the page on scroll. Can anyone help? Thanks in advance.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sticky-Graphic</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<section class="one">
<div class="graphic">
<div class="child">
<img src="SVG/triangle.svg" class="triangle" width="150px"/>
<img src="SVG/circle.svg" class="circle" width="150px"/>
<img src="SVG/rectangle.svg" class="rectangle" width="150px"/>
</div>
</div>
</section>
<section class="two">
</section>
<section class="three">
</section>
</body>
</html>type here
CSS
*{
margin: 0;
padding:0;
box-sizing: border-box;
}
.graphic {
display:flex;
justify-content: center;
align-items: center;
height: 100%;
width: 100%;
position:relative;
}
.child{
position: sticky;
top:0;
}
.triangle, .circle, .rectangle {
position: absolute;
}
section{
height: 100vh;
}
.one{
background:rgb(72, 72, 171) ;
}
.two{
background: pink;
}
.three{
background: orange;
}
2
Answers
I have had the same problem, and this is not a bug. This is how css works! I have the answer:
When you said
position: sticky; top: 0;
you needed to replace withposition: fixed
! easy mistake. although idk abouttop: 0;
, you may need to dotop: 0px;
or other measurements.If I sound weird, this is my 1st answer.
I hope this helps!
Sticky items are only sticky within their parent element. So if you want a sticky element to be visible throughout the entire document, it needs to be at the top level — a child of the body element.
This snippet demonstrates the idea. Note that the images/graphics are children of the body element, they are not wrapped in any sections or divs. I have used raster images rather than SVG graphics, but it will work the same with SVGs.