Computer >> Máy Tính >  >> Lập trình >> CSS

Làm thế nào để tạo một thanh điều hướng cố định khi cuộn bằng CSS?

Bằng cách chỉ định thuộc tính vị trí CSS, chúng tôi có thể tạo một thanh điều hướng cố định bằng cách sử dụng CSS.

Cú pháp của thuộc tính vị trí trong CSS như sau -

Selector {
   position: /*value*/;
}

Sau đây là một ví dụ về thuộc tính vị trí CSS.

Ví dụ

<!DOCTYPE html>
<html>
<head>
<style>
#navigation-bar {
   overflow: hidden;
   box-shadow: inset 0 0 20px green;
}
a {
   float: left;
   display: block;
   margin-left: 2%;
   padding: 2% 4%;
   text-align: center;
   color: black;
   text-decoration: none;
   font-size: 1.2em;
   border: 0.5px ridge red;
}
a:hover {
   box-shadow: inset 0 0 14px red;
   font-size: 1.6em;
}
.content {
   background-color: coral;
   padding: 16px;
}
.sticky {
   position: fixed;
   top: 0;
   width: 100%;
}
.sticky + .content {
   padding-top: 80px;
}
</style>
</head>
<body>
<div class="content"></div>
<div id="navigation-bar">
<a class="active" href="#">logo</a>
<a href="#">SignUp</a>
<a href="#">SignIn</a>
<a href="#">More</a>
</div>
<div class="content">
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum faucibus ante quis odio rhoncus, sit amet porta nunc venenatis. Vivamus eu ex et risus vehicula semper eu eu elit. Aliquam tempor rutrum neque sit amet aliquam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Cras non eros ex. Suspendisse placerat tincidunt tortor a semper. Etiam molestie justo ac sapien auctor maximus. Etiam ut ante sollicitudin, tempor mauris nec, malesuada purus. Nunc malesuada sem sed fermentum eleifend. Cras ultrices velit eu blandit lobortis.
</p>
<img src="https://images.unsplash.com/photo-1612305876291-
c369fea489b3?crop=entropy&cs=tinysrgb&fit=crop&fm=jpg&h=800&ixlib=rb1.2.1&q=80&w=600" />
</div>
<script>
let nav = document.getElementById("navigation-bar");
let sticky = nav.offsetTop;
window.onscroll = function() {sticker()};
function sticker() {
   if (window.pageYOffset >= sticky) {
      nav.classList.add("sticky")
   } else {
      nav.classList.remove("sticky");
   }
}
</script>
</body>
</html>

Đầu ra

Điều này sẽ tạo ra kết quả sau -

Làm thế nào để tạo một thanh điều hướng cố định khi cuộn bằng CSS?

Làm thế nào để tạo một thanh điều hướng cố định khi cuộn bằng CSS?