dsp_user
dsp_user

Reputation: 2121

Html div layout with fixed position

I rarely do html/css stuff so I'm struggling trying to implement what seems like a pretty basic layout. I have a bunch of div elements stacked vertically as well as centered horizontally across my html page. The problems I'm facing are

a) the top div (orange) is slightly wider than the other divs.

b) I want the top (orange) div to be visible even when scrolling, which currently isn't the case.

Actually, in order to make the top div always visible, I set its corresponding class' position attribute to fixed but it doesn't work since I also have other divs, and their position is set to relative. If I remove the relative position on the other divs, the orange div works as expected but the rest of divs are not horizontally centered anymore.

.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>

This is what it looks like now (when scrolling the top div is covered by other divs, and I don't want that)

enter image description here

Upvotes: 0

Views: 240

Answers (1)

G-Cyrillus
G-Cyrillus

Reputation: 106048

position:sticky might be what you look for : see 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>

Upvotes: 2

Related Questions