【问题标题】:Html div layout with fixed position具有固定位置的 Html div 布局
【发布时间】:2020-06-18 01:33:46
【问题描述】:

我很少做 html/css 的东西,所以我很难尝试实现看起来很基本的布局。我有一堆垂直堆叠的 div 元素,以及在我的 html 页面上水平居中的元素。我面临的问题是

a) 顶部 div(橙色)比其他 div 稍宽。

b) 我希望顶部(橙色)div 即使在滚动时也可见,但目前并非如此。

其实,为了让顶部的div始终可见,我将其对应类的位置属性设置为固定,但它不起作用,因为我还有其他div,并且它们的位置设置为相对。如果我删除其他 div 上的相对位置,橙色 div 会按预期工作,但其余 div 不再水平居中。

.fiksan {
  background-color: orange;
  position: fixed;
  top: 0;
  height: 40px;
}

div {
  padding: 10px;
  color: white;
  width: 60%;
  left: 20%;
  position: relative;
  top: 40px;
}

.naslov {
  background-color: lightblue;
  text-align: justified;
  height: 180px;
  position: relative;
}

.elementi {
  background-color: blue;
  height: 650px;
}

.css_elementi {
  background-color: purple;
  height: 400px;
  position: relative;
}
<div class="fiksan">
</div>

<div class="naslov">

</div>

<div class="elementi">

</div>

<div class="css_elementi">

</div>

这就是现在的样子(当滚动顶部的 div 被其他 div 覆盖时,我不希望这样)

【问题讨论】:

  • 是的,是 position: fixedtop: 0 相结合,给您带来了问题。下面的答案就是解决方法!

标签: html css


【解决方案1】:

position:sticky 可能就是您要找的东西:请参阅https://css-tricks.com/position-sticky-2/

.fiksan {
  background-color: orange;
  position: sticky;
  top: 0;
  height: 40px;
}

div {
  padding: 10px;
  color: white;
  width: 60%;
margin:auto;
 
}

.naslov {
  background-color: lightblue;
  text-align: justified;
  height: 180px; 
}

.elementi {
  background-color: blue;
  height: 650px;
}

.css_elementi {
  background-color: purple;
  height: 400px; 
}
<div class="fiksan">
</div>

<div class="naslov">

</div>

<div class="elementi">

</div>

<div class="css_elementi">

</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-21
    • 1970-01-01
    • 2018-08-09
    • 1970-01-01
    • 1970-01-01
    • 2015-10-21
    • 1970-01-01
    相关资源
    最近更新 更多