HTML div布局与固定位置

时间:2020-06-17 17:30:26

标签: html css

我很少做html / css的工作,所以我在努力实现看起来很基本的布局。我有一堆div元素垂直堆叠以及在HTML页面中水平居中。我面临的问题是

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

b)我希望即使滚动时也能看到顶部(橙色)的div,目前情况并非如此。

实际上,为了使顶部div始终可见,我将其对应的class的position属性设置为fixed,但是由于我还有其他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覆盖时,我不希望这样)

enter image description here

1 个答案:

答案 0 :(得分:2)

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>