β€οΈβπ₯How to Create a header line that appears when a user scrolls using HTML, CSS, and JavaScript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
body, html {
margin: 0;
padding: 0;
height: 200%;
font-family: Arial, sans-serif;
}
.header-line {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 4px;
background-color: blue;
transform: translateY(-100%);
transition: transform 0.3s ease;
}
.content {
padding: 20px;
}
</style>
</head>
<body>
<div class="header-line" id="headerLine"></div>
<div class="content">
<!-- Add lots of content here to enable scrolling -->
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque vitae vehicula nunc, in consectetur libero. Nullam id tincidunt risus, eget venenatis lectus. Suspendisse potenti. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae; Vivamus auctor ligula nec turpis pharetra, in dignissim mauris tempus. Nam vitae ante volutpat, elementum lorem ut, posuere sem. Maecenas eget sem ultricies, consequat mi sed, commodo nisl.</p>
<!-- Repeat the paragraph above or add more content to allow scrolling -->
</div>
<script>
window.addEventListener('scroll', () => {
const headerLine = document.getElementById('headerLine');
if (window.scrollY > 50) {
headerLine.style.transform = 'translateY(0)';
} else {
headerLine.style.transform = 'translateY(-100%)';
}
});
</script>
</body>
</html>
Explain :
HTML:
We create a
div
element with a class ofheader-line
that will act as our header line.We also create a
div
with a class ofcontent
to contain enough text to make the page scrollable.
CSS:
We set up basic styling for the body and HTML to ensure the page has enough height and a sans-serif font.
The
.header-line
class styles the header line to be fixed at the top of the page, with an initial transform property to hide it above the viewport.A smooth transition is set for the transform property to allow the header line to slide down smoothly when the user scrolls.
JavaScript:
We add an event listener for the
scroll
event.In the event handler, we check the
scrollY
property (the number of pixels the document has already been scrolled vertically).If the
scrollY
value is greater than 50 pixels, we set thetransform
property of the header line totranslateY(0)
to slide it into view.If the
scrollY
value is 50 pixels or less, we hide the header line by setting thetransform
property back totranslateY(-100%)
.
Last updated