【问题标题】:Creating a parallax page and positioning elements within the sections创建视差页面并在部分内定位元素
【发布时间】:2016-03-09 08:39:20
【问题描述】:

我目前正在构建一个视差页面,但在将元素定位在部分上时遇到了问题。因此我的问题是绝对定位。

有没有办法让绝对位置只在一个部分而不是整个页面/视口中起作用?

我做了一个非常简单的例子来说明我正在尝试做的事情:https://jsfiddle.net/zu2epxxq/1/

如您所见,#second 部分内的段落应位于该部分内,而不是主要部分 #first。显然这是使用绝对定位的副作用。 我如何以干净和良好的方式解决这个问题?

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

【问题讨论】:

  • 我没有看到position: relative 的任何absolute 元素。你可能需要这个。

标签: html css parallax absolute


【解决方案1】:

使用“位置:相对;”上的部分。然后,您可以相对于部分元素定位子元素。

我做了这个: https://jsfiddle.net/hpepwvdg/1/

但我更喜欢使用 flexbox 布局模式,因为我发现了 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>

【讨论】:

  • 与我使用的传统方法相比,使用 flex-box 有什么好处吗?
  • 我只是无法让它与您的方法一起使用。不知道我做错了什么。从那里我决定用 flexbox 制作一个代码片段,因为我认为它更容易。 Flexbox 非常强大,唯一的问题是对 IE 的支持,目前还不是很好。但即便如此,如果你从事前端 Web 开发,我建议你看看这个:a-guide-to-flexbox
  • 我可以使用与绝对定位等相同的功能吗?
  • 是的,你可以,我又试了一次,并成功了:jsfiddle.net/hpepwvdg/1
猜你喜欢
  • 2012-02-05
  • 1970-01-01
  • 1970-01-01
  • 2012-02-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-24
相关资源
最近更新 更多