Search code examples
htmlcssparallaxabsolute

Creating a parallax page and positioning elements within the sections


I am currently building a parallax page, but I have problems positioning the elements on the sections. Hence my problem is absolute positioning.

Is there any way to make the absolute position to work within a section only instead of the entire page/viewport?

I have made a very minimal example of what I am trying to do: https://jsfiddle.net/zu2epxxq/1/

As you can see the paragraph within #second section should position inside of that section and not the main section #first. Obviously this is a side-effect of using absolute positioning. How do I solve this in a clean and good manner?

HTML:

<section id="first">
  <div>
    <p>This is a test</p>
  </div>
</section>
<section id="second">
  <div>
    <p>More text that has to be pushed arund in this section</p>
  </div>
</section>

CSS:

html,
body {
  height: 100%;
  color: #fff;
  font-size: 16px;
  margin: 0;
  padding: 0;
}

section {
  min-height: 100%;
}

#first {
  background-color: #000;
}

#second {
  background-color: #ddd;
}

section > div {
  bottom: 0;
  margin: 0;
  font-size: 4em;
  position: absolute;
  transform: translate(-50%, 50%);
  left: 50%;
}

Solution

  • Use "position: relative;" on the sections. You then can position the child elements relative to the section elements.

    I made this out of it: https://jsfiddle.net/hpepwvdg/1/

    But I prefer using the flexbox layout mode since I discovered the power of flexbox: (http://www.w3schools.com/css/css3_flexbox.asp):

    html, body, .container {
        height: 100%;
          color: #fff;
    }
    .container {
        display: -webkit-flexbox;
        display: -ms-flexbox;
        display: -webkit-flex;
        display: flex;
        -webkit-flex-align: center;
        -ms-flex-align: center;
        -webkit-align-items: center;
        align-items: center;
        justify-content: center;
    }
    
    #first {
        background-color: #000;
    }
    
    #second {
        background-color: #ddd;
    }
    
    .centered_heading {
        font-size: 4em;
    }
    <section class="container" id="first">
      <h1 class="centered_heading">Centered!</h1>
    </section>
    
    <section class="container" id="second">
      <h1 class="centered_heading">Centered!</h1>
    </section>