放置固定的元素而不将其从文档流中删除

时间:2019-01-16 13:17:04

标签: html css css-grid

我在HTML代码中包含三个元素。我想将元素固定在右侧而不要将其从文档流中移除。

<div class="container">
   <header class="main-header">
   </header>
   <main class="main-content">
   </main>
   <footer class="main-footer">
   </footer>
</div>

这是我正在使用的CSS代码

.container {
   display: grid;
   grid-template-columns: 1fr 3fr;
   grid-template-rows: auto auto;
}
.main-header{
   grid-column: 1/2;
   grid-row: 1/3;
   /* Here i want this to be fixed (scrolling should not have any effect)*/
   position: fixed;
  }

固定的位置将其从“文档”流中删除,所有内容看起来都很难看。 任何人都可以告诉我如何在不使用position:fixed;的情况下实现这一目标。或不将其从文档流中删除。

2 个答案:

答案 0 :(得分:1)

只需保持标题不变,并为.main-content设置一个与标题高度一样大的填充顶部,或者就美学而言甚至更高。

.main-header{
  grid-column: 1/2;
  grid-row: 1/3;
  /* Here i want this to be fixed (scrolling should not have any effect)*/
  position: fixed;
  top: 0;
  height: 80px;
}
.main-content {
  padding-top: 100px;
  width: 100%;
  float: left;
}

答案 1 :(得分:1)

header周围添加其他包装元素,然后将position:sticky应用于header

我假设您的意思是固定在 left 而不是 right ,因为这似乎就是您的示例。

* {
  margin: 0;
}

.con {
  display: grid;
  grid-template-columns: 1fr 3fr;
  grid-template-rows: auto auto;
}

.wrap {
  background: gray
}

header {
  color: white;
  text-align: center;
  grid-area: 1 / 1 / 3 / 2;
  position: sticky;
  top: 0;
}

main {
  background: rgba(0, 0, 200, 0.4);
  height: 2000px;
  padding-top: 10px;
}

footer {
  text-align: center;
  background: black;
  color: white;
}
<div class="con">
  <div class="wrap">
    <header>
      <h2>Someone</h2>
      <p>Lorem ipsem</p>
      <p>lorem Ipsem</p>
      <p>lorem ipsem</p>
    </header>
  </div>
  <main>
    <h1>Heading</h1>
    <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Recusandae molestias maiores voluptates, suscipit eveniet vitae harum id? Fugiat labore eligendi delectus, ipsum molestiae numquam ex inventore deleniti deserunt quia perspiciatis!</p>
    <h2>heading 2</h2>
    <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Omnis atque enim possimus error voluptas distinctio eos vel? Dolorem alias voluptas minus sunt asperiores consequuntur! Sit harum qui culpa ea assumenda!
    </p>
    <h2>heaing 2</h2>
    <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Quam ut reprehenderit vero perferendis aspernatur, rerum asperiores! Aperiam aliquam commodi quod dolores, unde optio repellat necessitatibus facere, laborum expedita enim soluta.
    </p>
  </main>
  <footer>
    <p>Made by Zullu</p>
  </footer>
</div>