Как создать фиксированный верхний раздел, не нарушая работу его элементов?

#html #css #fixed

#HTML #css #исправлено

Вопрос:

Я добавил position: fixed; в верхний раздел, где размещены меню и логотип. Он продолжал показывать меню при прокрутке вниз, но это также нарушило порядок и пространство логотипа и меню. Есть ли способ преодолеть эту проблему? или альтернативный способ сохранить меню при прокрутке вниз?

Раздел, который я хочу сохранить при прокрутке вниз

Нежелательный результат

 html {
  scroll-behavior: smooth;
}

body {
  background: #fafafa;
}

.grid-container {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr 1fr;
  grid-template-rows: 1fr 3fr 3fr 3fr 2fr;
  grid-template-areas: "logo . menu menu" "hi hi hi hi" "what what what what" "projects projects projects projects""contact contact contact contact";
}

.logo {
  background: #fafafa;
  grid-area: logo;
  display: flex;
  justify-content: center;
  justify-items: center;
  position: fixed;
}

.logo img {
  object-fit: contain;
}

.menu {
  display: flex;
  grid-area: menu;
  background-color: #fafafa;
  text-align: center;
  align-items: center;
  justify-content: center;
  position: fixed;
}

.menu a {
  position: relative;
  cursor: pointer;
  font-size: 20px;
  font-family: 'Roboto', sans-serif;
  text-decoration: none;
  color: black;
}

.menu a a {
  margin-left: 1rem;
}

.menu a::after {
  content: "";
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 2px;
  transform: scaleX(0);
  transition: transform 0.4s ease;
  transform-origin: bottom right;
  background-color: #ff9c00;
}

.menu a:hover::after {
  transform-origin: bottom left;
  transform: scaleX(1);
}

.hi {
  grid-area: hi;
  background-color: #c2edda;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.hi img {
  max-width: 100%;
  width: 37em;
  animation: fadein 2s;
  padding: 150px 150px 150px 50px;
}

@keyframes fadein {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

@media screen and (max-width: 1080px) {
  .hi {
    justify-content: flex-end;
  }
  .hi p {
    font-size: 20px !important;
  }
}

@media screen and (max-width: 870px) {
  .hi img {
    display: none;
  }
  .hi {
    justify-content: center;
  }
}

.hi p {
  font-size: 35px;
  text-align: center;
  font-family: 'Roboto';
}

.what {
  padding: 50px 50px 50px 50px;
  font-family: 'Roboto';
  grid-area: what;
  background-color: #fafafa;
  display: flex;
  justify-items: center;
  justify-content: center;
}

.what img {
  object-fit: contain;
  width: 15%;
  height: auto;
  position: absolute;
  margin-top: 100px;
}

.projects {
  font-family: 'Roboto';
  display: flex;
  justify-content: center;
  padding: 50px 50px;
  grid-area: projects;
  background-color: khaki;
}

.pContainer {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr 1fr;
  grid-template-rows: 1fr 1fr 1fr;
  gap: 1px 1px;
  grid-template-areas: ". headline headline ." "p1 p2 p3 p4" ". . . .";
  justify-content: space-between;
}

.headline {
  grid-area: headline;
  display: flex;
  justify-content: center;
}

.p1 {
  grid-area: p1;
}

.p2 {
  grid-area: p2;
  display: flex;
  justify-content: center;
}

.p3 {
  grid-area: p3;
  display: flex;
  justify-content: center;
}

.p4 {
  grid-area: p4;
}

.contact {
  grid-area: contact;
  background-color: steelblue;
}  
 <div class="grid-container">
  <div class="logo"><img src="logo.png"></div>
  <div class="menu">
    <ul>
      <a href="#who" class="list-inline-item">Who</a>
      <a href="#skills" class="list-inline-item">What</a>
      <a href="#proj" class="list-inline-item">Projects</a>
      <a class="list-inline-item">Contact</a>
    </ul>
  </div>
  <div id="who" class="hi">
    <img src="photo.png" alt="photo">
    <p id="para">
      Hi! I'm Avichai, <br> I'm a 22 y/o junior web developer and designer. <br> My knowledge is based mainly <br> on my high school computer science extension, <br> my continuous self-learning and curisity.
    </p>
  </div>
  <div id="skills" class="what">
    <h1>Knowledge and Skills</h1>
    <img src="3logo.png">
  </div>

  <div id="proj" class="projects">


    <div class="pContainer">
      <div class="headline">
        <h1>Projects</h1>
      </div>
      <div class="p1"></div>
      <div class="p2">Lone Soldier Realty</div>
      <div class="p3">Freelance Graphic Design</div>
      <div class="p4"></div>
    </div>
    <div id="contact" class="contact">


    </div>

  </div>  

Ссылка на GitHub на код веб-сайта

Большое вам спасибо. 🙂

Комментарии:

1. Привет, Avihyb. Вы должны создать рабочий пример здесь, в stackoverflow, вместо ссылки на источник github, где находится ваш код. Потратьте несколько минут и сделайте это, и это поможет вашим изменениям получить справку. Я мог легко увидеть, что этот вопрос скоро будет закрыт, если вы этого не сделаете. Думал, что я предупреждаю вас.

2. Итак, сделайте копию всего исходного кода html и CSS?

3. В вашем случае я бы сказал, используйте полный исходный код и css. В других случаях вы могли бы просто выбрать соответствующие элементы и css, например, вам не нужно включать нижний колонтитул и часть содержимого, если на это не влияет ошибка.

4. Добавлено. Большое тебе спасибо, Деян, оценил!

Ответ №1:

Для этого position: sticky хорошо.

Что я сделал, так это поместил ваш логотип и ссылки в 1 div с display:flex

Затем я переместил его из области сетки вверху и дал ему position: sticky: top: 0;

Это означает, что ваш элемент будет первым относительным. Если элемент достигнет top: 0 , он будет придерживаться его

Небольшое замечание здесь: обычно мы устанавливаем сброс полей, отступов и размеров полей вверху.

Нравится:

 html {
   padding: 0;
   margin: 0;
   box-sizing: border-box;
}
  

 html {
  scroll-behavior: smooth;
}

body {
  background: #fafafa;
  margin: 0;
  padding: 0;
  box-sizing:border-box;
}

.grid-container {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr 1fr;
  grid-template-rows: 0fr 3fr 3fr 3fr 2fr;
  grid-template-areas: "logo . menu menu" "hi hi hi hi" "what what what what" "projects projects projects projects""contact contact contact contact";
}

.logo {
  background: #fafafa;
  grid-area: logo;
  display: flex;
  justify-content: center;
  justify-items: center;
}

.logo img {
  object-fit: contain;
}

.menu {
  display: flex;
  grid-area: menu;
  background-color: #fafafa;
  text-align: center;
  align-items: center;
  justify-content: center;
}

.menu a {
  position: relative;
  cursor: pointer;
  font-size: 20px;
  font-family: 'Roboto', sans-serif;
  text-decoration: none;
  color: black;
}

.menu a a {
  margin-left: 1rem;
}

.menu a::after {
  content: "";
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 2px;
  transform: scaleX(0);
  transition: transform 0.4s ease;
  transform-origin: bottom right;
  background-color: #ff9c00;
}

.menu a:hover::after {
  transform-origin: bottom left;
  transform: scaleX(1);
}

.hi {
  grid-area: hi;
  background-color: #c2edda;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.hi img {
  max-width: 100%;
  width: 37em;
  animation: fadein 2s;
  padding: 150px 150px 150px 50px;
}

@keyframes fadein {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

@media screen and (max-width: 1080px) {
  .hi {
    justify-content: flex-end;
  }
  .hi p {
    font-size: 20px !important;
  }
}

@media screen and (max-width: 870px) {
  .hi img {
    display: none;
  }
  .hi {
    justify-content: center;
  }
}

.hi p {
  font-size: 35px;
  text-align: center;
  font-family: 'Roboto';
}

.what {
  padding: 50px 50px 50px 50px;
  font-family: 'Roboto';
  grid-area: what;
  background-color: #fafafa;
  display: flex;
  justify-items: center;
  justify-content: center;
}

.what img {
  object-fit: contain;
  width: 15%;
  height: auto;
  position: absolute;
  margin-top: 100px;
}

.projects {
  font-family: 'Roboto';
  display: flex;
  justify-content: center;
  padding: 50px 50px;
  grid-area: projects;
  background-color: khaki;
}

.pContainer {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr 1fr;
  grid-template-rows: 1fr 1fr 1fr;
  gap: 1px 1px;
  grid-template-areas: ". headline headline ." "p1 p2 p3 p4" ". . . .";
  justify-content: space-between;
}

.headline {
  grid-area: headline;
  display: flex;
  justify-content: center;
}

.p1 {
  grid-area: p1;
}

.p2 {
  grid-area: p2;
  display: flex;
  justify-content: center;
}

.p3 {
  grid-area: p3;
  display: flex;
  justify-content: center;
}

.p4 {
  grid-area: p4;
}

.contact {
  grid-area: contact;
  background-color: steelblue;
}

.stickybar {
   display: flex;
   align-items: center;
   justify-content: space-between;
   position: sticky;
   top: 0;
   background: #fafafa;
   padding: 0 10px;
   z-index: 1;
}  
 <div class="stickybar">
  <div class="logo"><img src="https://raw.githubusercontent.com/avihyb/avihyb.github.io/master/LOGO.png"></div>
     <div class="menu">
       <ul>
         <a href="#who" class="list-inline-item">Who</a>
         <a href="#skills" class="list-inline-item">What</a>
         <a href="#proj" class="list-inline-item">Projects</a>
         <a class="list-inline-item">Contact</a>
       </ul>
     </div>
  </div>
<div class="grid-container">

  <div id="who" class="hi">
    <img src="photo.png" alt="photo">
    <p id="para">
      Hi! I'm Avichai, <br> I'm a 22 y/o junior web developer and designer. <br> My knowledge is based mainly <br> on my high school computer science extension, <br> my continuous self-learning and curisity.
    </p>
  </div>
  <div id="skills" class="what">
    <h1>Knowledge and Skills</h1>
    <img src="3logo.png">
  </div>

  <div id="proj" class="projects">


    <div class="pContainer">
      <div class="headline">
        <h1>Projects</h1>
      </div>
      <div class="p1"></div>
      <div class="p2">Lone Soldier Realty</div>
      <div class="p3">Freelance Graphic Design</div>
      <div class="p4"></div>
    </div>
    <div id="contact" class="contact">


    </div>

  </div>  

Комментарии:

1. Вы также можете включить z-index , чтобы изображение не перекрывалось

Ответ №2:

Надеюсь, это может вам помочь.

Вы должны поместить и логотип, и меню в одну оболочку, чтобы в нашем случае заголовок наилучшим образом соответствовал оболочке, а затем добавить позицию, фиксированную на этой оболочке.

Поместите фиксированную позицию в оболочку заголовка вместо меню и логотипа.

Кроме того, я добавил отображение flex в заголовке и сделал его пробелом между и выровнял по центру.

  html{
      scroll-behavior: smooth;
}
body{
      background: #fafafa;  
}
.grid-container {
    display: grid;
    grid-template-columns: 1fr 1fr 1fr 1fr;
    grid-template-rows: 1fr 3fr 3fr 3fr 2fr;
        
    grid-template-areas: "logo . menu menu" "hi hi hi hi" "what what what what" "projects projects projects projects""contact contact contact contact" ;
  }
  
  .logo { 
        background: #fafafa;
        grid-area: logo; 

        }
  
        .logo img{

            object-fit: contain;
        }
header.header{
          position: fixed;
          left:0;
          right:0; 
              display: flex;
    justify-content: space-between;
    align-items: center;
    padding:10px;
       background:#fafafa;
    }
  .menu { 
          
          grid-area: menu; 
          background-color: #fafafa;
        

          
          
        }
        .menu a{
              position: relative;
              cursor: pointer;
              font-size:20px;
              font-family: 'Roboto', sans-serif;
              text-decoration: none;
              color: black;
            }

      .menu a   a{
            margin-left: 1rem;
      }
      .menu a::after{
            content:"";
            position: absolute;
            bottom: 0;
            left: 0;
            width: 100%;
            height: 2px;
            transform: scaleX(0);
            transition: transform 0.4s ease;
            transform-origin: bottom right;
            background-color: #ff9c00;

      }
  
      .menu a:hover::after{
            transform-origin: bottom left;
            transform: scaleX(1);
      }
  .hi { 
        grid-area: hi;
        background-color: #c2edda;
        height:100%;
        display: flex;
        justify-content: center;
        align-items: center;
        
      }

      .hi img{
            max-width: 100%;
            width: 37em;
            animation: fadein 2s;
            padding:150px 150px 150px 50px ;
      }
      @keyframes fadein {
            from { opacity: 0; }
            to   { opacity: 1; }
        }

      @media screen and (max-width: 1080px)
      {
            .hi{justify-content: flex-end;}
            .hi p{font-size: 20px !important;}
            
      }
      @media screen and (max-width: 870px)
      {
            .hi img{display: none;}
            .hi{justify-content: center;}
      }
  
      .hi p{
            font-size: 35px;
            text-align: center;
            font-family: 'Roboto';
      }
  .what {
      padding:50px 50px 50px 50px ;

         font-family: 'Roboto';
         grid-area: what;
         background-color: #fafafa;
         display: flex;
         justify-items: center;
         justify-content: center;
         
        }   
        .what img{
              object-fit: contain;
              width: 15%;
              height: auto;
              position: absolute;
              margin-top: 100px;
        }
  
        .projects{
            font-family: 'Roboto';
              display: flex;
              justify-content: center;
              padding: 50px 50px;
              grid-area: projects;
              background-color: khaki;
        }

        .pContainer{

            display: grid;
            grid-template-columns: 1fr 1fr 1fr 1fr;
            grid-template-rows: 1fr 1fr 1fr;
            gap: 1px 1px;
            grid-template-areas:
              ". headline headline ."
              "p1 p2 p3 p4"
              ". . . .";
              justify-content: space-between;
        }

      .headline { grid-area: headline;
      display: flex;
justify-content: center; }

      .p1 { grid-area: p1; }

      .p2 { grid-area: p2;
            display: flex;
            justify-content: center;  }

      .p3 { grid-area: p3;
            display: flex;
            justify-content: center;
             }

      .p4 { grid-area: p4; }


  .contact { 
         grid-area: contact;
         background-color: steelblue;
        }  
 <!DOCTYPE html>
<html lang="en">
<head>
  
  <script src="script.js"></script>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP VmmDGMN5t9UJ0Z" crossorigin="anonymous">
    <title>Avichai</title>
    <style>
      @import url('https://fonts.googleapis.com/css2?family=Roboto:wght@100amp;display=swap');
      </style> 
      <link rel="icon" href="logo.png" >
         <link rel="stylesheet" href="/style.css">
         <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    
</head>
<body>
   <div class="grid-container">
   <header class="header">
  <div class="logo"><img src="https://raw.githubusercontent.com/avihyb/avihyb.github.io/master/LOGO.png" class="img-fluid" width="180" height="82"></div>
  <div class="menu">
    <ul>
      <a href="#who" class="list-inline-item">Who</a>
      <a href="#skills" class="list-inline-item">What</a>
      <a href="#proj" class="list-inline-item">Projects</a>
      <a class="list-inline-item">Contact</a>
    </ul>
  </div>
  </header>
  <div id="who" class="hi">
    <img src="photo.png" alt="photo" />
    <p id="para">
      Hi! I'm Avichai, <br>
      I'm a 22 y/o junior web developer and designer. <br>
      My knowledge is based mainly <br> on my high school computer science extension, <br>
      my continuous self-learning and curisity.
    </p>
  </div>
    <div id="skills" class="what"><h1>Knowledge and Skills</h1>
      <img src="3logo.png">
  </div>

  <div id="proj" class="projects">
    
    
    <div class="pContainer">
      <div class="headline"><h1>Projects</h1></div>
      <div class="p1"></div>
      <div class="p2">Lone Soldier Realty</div>
      <div class="p3">Freelance Graphic Design</div>
      <div class="p4"></div>
    </div>
  <div id="contact"class="contact">


  </div>

</div>

</body>
</html>  

Комментарии:

1. итак, что вы сделали и объясните почему?

2. Хаха, потрясающе. Я попытаюсь выяснить из кода, что изменилось. Но можете ли вы дать общее представление о вашем решении?

3. привет @Dejan. Прошу прощения за неудобства. Я писал свое объяснение, пока вы комментировали.

4. привет @avihyb извините за неудобства. Я кратко изложил.

5. @avihyb В этом есть и еще кое-что. Вы захотите изучить все настройки для display в ответе Пракаша.

Ответ №3:

Прежде всего, я добавил div в качестве навигационной панели внутри логотипа и меню.

   <div class="navbar">
    <div class="logo"><img src="https://raw.githubusercontent.com/avihyb/avihyb.github.io/master/LOGO.png"></div>
    <div class="menu">
      <ul>
        <a href="#who" class="list-inline-item">Who</a>
        <a href="#skills" class="list-inline-item">What</a>
        <a href="#proj" class="list-inline-item">Projects</a>
        <a class="list-inline-item">Contact</a>
      </ul>
    </div>
  </div>
  

Поскольку вы исправили как логотип, так и меню, он изменяется только на фиксированную панель навигации, которая находится внутри них.
затем добавлен цвет фона в панель навигации;

 .navbar{
  display:flex;
  flex-wrap:wrap;
  background-color: #fafafa;
  position: fixed;
  top:0;
  left:0;
  right:0;
  width:100%;
  z-index:9999; // for images overlaying the navbar.
}
  

затем добавьте width:20%; к логотипу также ширину

 .logo {
  display: flex;
  justify-content: center;
  width:20%;
}
  

и width:75%; и margin-right:5%; в меню

 .menu {
  width:75%;
  margin-right:5%;
}
  

Попробуйте демо.

 html {
  scroll-behavior: smooth;
}

body {
  background: #fafafa;
}

.grid-container {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr 1fr;
  grid-template-rows: 0fr 3fr 3fr 3fr 2fr;
  grid-template-areas: "logo . menu menu" "hi hi hi hi" "what what what what" "projects projects projects projects""contact contact contact contact";
}

.logo {
  background: #fafafa;
  grid-area: logo;
  display: flex;
  justify-content: center;
  align-items:center;
  width:25%;
}

.logo img {
  object-fit: contain;
}

.menu {
  display: flex;
  grid-area: menu;
  background-color: #fafafa;
  text-align: center;
  align-items: center;
  justify-content: center;
  height:104px;
  width:75%;

}
.navbar{
  display:flex;
  flex-wrap:wrap;
  background-color: #fafafa;
  position: fixed;
  top:0;
  left:0;
  right:0;
  width:100%;
  z-index:9999;
}
.menu a {
  position: relative;
  cursor: pointer;
  font-size: 20px;
  font-family: 'Roboto', sans-serif;
  text-decoration: none;
  color: black;
}

.menu a a {
  margin-left: 1rem;
}

.menu a::after {
  content: "";
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 2px;
  transform: scaleX(0);
  transition: transform 0.4s ease;
  transform-origin: bottom right;
  background-color: #ff9c00;
}

.menu a:hover::after {
  transform-origin: bottom left;
  transform: scaleX(1);
}

.hi {
  grid-area: hi;
  background-color: #c2edda;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.hi img {
  max-width: 100%;
  width: 37em;
  animation: fadein 2s;
  padding: 150px 150px 150px 50px;
}

@keyframes fadein {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

@media screen and (max-width: 1080px) {
  .hi {
    justify-content: flex-end;
  }
  .hi p {
    font-size: 20px !important;
  }
}

@media screen and (max-width: 870px) {
  .hi img {
    display: none;
  }
  .hi {
    justify-content: center;
  }
}

.hi p {
  font-size: 35px;
  text-align: center;
  font-family: 'Roboto';
}

.what {
  padding: 50px 50px 50px 50px;
  font-family: 'Roboto';
  grid-area: what;
  background-color: #fafafa;
  display: flex;
  justify-items: center;
  justify-content: center;
}

.what img {
  object-fit: contain;
  width: 15%;
  height: auto;
  position: absolute;
  margin-top: 100px;
}

.projects {
  font-family: 'Roboto';
  display: flex;
  justify-content: center;
  padding: 50px 50px;
  grid-area: projects;
  background-color: khaki;
}

.pContainer {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr 1fr;
  grid-template-rows: 1fr 1fr 1fr;
  gap: 1px 1px;
  grid-template-areas: ". headline headline ." "p1 p2 p3 p4" ". . . .";
  justify-content: space-between;
}

.headline {
  grid-area: headline;
  display: flex;
  justify-content: center;
}

.p1 {
  grid-area: p1;
}

.p2 {
  grid-area: p2;
  display: flex;
  justify-content: center;
}

.p3 {
  grid-area: p3;
  display: flex;
  justify-content: center;
}

.p4 {
  grid-area: p4;
}

.contact {
  grid-area: contact;
  background-color: steelblue;
}  
 <div class="grid-container">
  <div class="navbar">
    <div class="logo"><img src="https://raw.githubusercontent.com/avihyb/avihyb.github.io/master/LOGO.png"></div>
    <div class="menu">
      <ul>
        <a href="#who" class="list-inline-item">Who</a>
        <a href="#skills" class="list-inline-item">What</a>
        <a href="#proj" class="list-inline-item">Projects</a>
        <a class="list-inline-item">Contact</a>
      </ul>
    </div>
  </div>
  <div id="who" class="hi">
    <img src="https://raw.githubusercontent.com/avihyb/avihyb.github.io/master/photo.png" alt="photo">
    <p id="para">
      Hi! I'm Avichai, <br> I'm a 22 y/o junior web developer and designer. <br> My knowledge is based mainly <br> on my high school computer science extension, <br> my continuous self-learning and curisity.
    </p>
  </div>
  <div id="skills" class="what">
    <h1>Knowledge and Skills</h1>
    <img src="https://raw.githubusercontent.com/avihyb/avihyb.github.io/master/3logo.png">
  </div>

  <div id="proj" class="projects">


    <div class="pContainer">
      <div class="headline">
        <h1>Projects</h1>
      </div>
      <div class="p1"></div>
      <div class="p2">Lone Soldier Realty</div>
      <div class="p3">Freelance Graphic Design</div>
      <div class="p4"></div>
    </div>
    <div id="contact" class="contact">


    </div>

  </div>  

Комментарии:

1. Большое вам спасибо. Как мне преодолеть проблему перекрытия с z-index? Должен ли я присвоить меню очень большое значение, чтобы оно было поверх всего?

2. Это имеет большое значение 🙂 для переполнения чего-либо настолько глупого, чувак 🙂