【问题标题】:HTML/CSS - My div is just not being sticky and I do not know why [duplicate]HTML/CSS - 我的 div 只是不粘,我不知道为什么[重复]
【发布时间】:2021-08-03 02:18:51
【问题描述】:

由于某种原因,我无法理解为什么这不起作用。我唯一的困难:标题 div 不是粘性的。

HTML:

<div class="header">
    <div class="header-content">
        <img src="mycoollogo.svg" class="logo" />
    </div>
</div>


CSS:
.logo {
  height: 3rem;
}

.header {
  position: -webkit-sticky; /* Safari Support */
  position: sticky;

  height: 3.5rem;
  margin-top: 0rem;
  margin-left: 0rem;
  margin-right: 0rem;

  background: var(--accent-color);

  color: white;
}

.header-content {
  height: 100%;
  display: flex;
  flex-direction: row;
  align-items: center;

  margin-left: 6rem;
  margin-right: 6rem;
}

【问题讨论】:

  • Position sticky 还需要您指定top 属性

标签: html css flexbox sticky


【解决方案1】:

您的代码看起来不错,我看到的唯一问题是您应该使用 top:0 以及粘贴位置来完成这项工作。

在这里,我对您的代码进行了一些修改,使其可见,使用下面的运行 sn-p 选项卡并尝试滚动,您的标题现在应该是粘性的。

.logo {
  height: 3rem;
}

.wrapper {
  position: relative;
}

.header {
  position: -webkit-sticky; /* Safari Support */
  position: sticky;
  top: 0;
  height: 3.5rem;
  margin-top: 0rem;
  margin-left: 0rem;
  margin-right: 0rem;

  background: var(--accent-color);

  color: white;
}

.header-content {
  height: 100%;
  display: flex;
  flex-direction: row;
  align-items: center;

  margin-left: 6rem;
  margin-right: 6rem;
}

.top-content {
  background: blue;
  height: 100px;
  position: sticky;
}

.bottom-content {
  background: red;
  height: 5000px;
}
<div class="wrapper">
  <div class="top-content"></div>
  <div class="header">
    <div class="header-content">
        <img src="mycoollogo.svg" class="logo" />
    </div>
</div>
<div class="bottom-content"></div>
</div>

【讨论】:

    【解决方案2】:

    尝试添加一个你希望它坚持的位置

    position: sticky;
    top: 0;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-16
      • 2022-12-14
      • 2021-11-16
      • 2021-04-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多