CSS sticky header
Creating a CSS sticky header using the position: sticky;
property. This property allows an element to be treated as relatively positioned until it crosses a specified point, after which it is treated as fixed.
Here’s a simple example of how you can create a sticky header using HTML and CSS:
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles.css">
<title>Sticky Header Example</title>
</head>
<body>
<header class="sticky-header">
<h1>Your Logo or Brand</h1>
<nav>
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Services</a></li>
<li><a href="#">Contact</a></li>
</ul>
</nav>
</header>
<!-- Rest of your content goes here -->
</body>
</html>
CSS (styles.css):
body {
margin: 0;
font-family: 'Arial', sans-serif;
}
.sticky-header {
background-color: #333;
padding: 10px 20px;
color: white;
position: sticky;
top: 0;
z-index: 1000;
}
.sticky-header h1 {
margin: 0;
font-size: 1.5em;
}
.sticky-header nav ul {
list-style-type: none;
margin: 0;
padding: 0;
display: flex;
}
.sticky-header nav ul li {
margin-right: 20px;
}
.sticky-header nav ul li:last-child {
margin-right: 0;
}
.sticky-header nav a {
text-decoration: none;
color: white;
font-weight: bold;
}
/* Add more styles as needed */
In this example, the key part is the .sticky-header
class. The position: sticky;
property is applied, and top: 0;
ensures that the header sticks to the top of the viewport. You can adjust the styles according to your design preferences. Feel free to modify the HTML and CSS to suit your specific requirements.