Creating a parallax page and positioning elements within the sections

送分小仙女□ 提交于 2019-12-12 05:13:20

问题


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%;
}

回答1:


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>


来源:https://stackoverflow.com/questions/35886673/creating-a-parallax-page-and-positioning-elements-within-the-sections

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!