June 3, 2024
Static, Relative, Absolute, Fixed, and Sticky Positioning
CSS positioning allows you to control the placement of elements on your web page. There are five main positioning types: static, relative, absolute, fixed, and sticky.
/* No need to specify position: static; since it's the default */
div {
position: relative;
top: 10px;
left: 20px;
}
div {
position: absolute;
top: 50px;
left: 100px;
}
div {
position: fixed;
top: 0;
right: 0;
width: 200px;
}
div {
position: sticky;
top: 0;
background-color: yellow;
}
Z-Index
The z-index
property determines the stack order of positioned elements (elements with a position value other than static). An element with a higher z-index
is always in front of an element with a lower z-index
.
Example:
div {
position: absolute;
top: 50px;
left: 50px;
z-index: 10;
}
Exercise: Creating a Fixed Navigation Bar
Let's create a fixed navigation bar using the positioning concepts we've learned.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Fixed Navigation Bar</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<nav>
<ul>
<li><a href="#home">Home</a></li>
<li><a href="#about">About</a></li>
<li><a href="#services">Services</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
</nav>
<section id="home"><h1>Home</h1></section>
<section id="about"><h1>About</h1></section>
<section id="services"><h1>Services</h1></section>
<section id="contact"><h1>Contact</h1></section>
</body>
</html>
body {
margin: 0;
font-family: Arial, sans-serif;
}
nav {
position: fixed;
top: 0;
width: 100%;
background-color: #333;
z-index: 1000;
}
nav ul {
list-style: none;
margin: 0;
padding: 0;
display: flex;
justify-content: space-around;
}
nav ul li {
margin: 0;
}
nav ul li a {
color: white;
text-decoration: none;
padding: 15px 20px;
display: block;
}
section {
padding: 100px 20px;
height: 100vh;
}
section
(odd) {
background-color: #f4f4f4;
}
section
(even) {
background-color: #fff;
}
Open the HTML file in a browser to see your fixed navigation bar. Experiment with different positioning values to see how they affect the layout and behavior of your elements.
Coming Up Next
In Chapter 7, we'll explore the Flexbox layout model, a powerful tool for creating flexible and responsive layouts with ease.
Please Sign In to post a comment.