保持div垂直居中于父元素

时间:2016-10-21 16:07:08

标签: javascript html css flexbox

目前我有一个包含以下代码的标题元素

<header>
    <div class="container">
        <div class="row" style="display: flex; justify-content: center">
            <div class="col-xs-12 text-center" style="align-self: center">
                <h1>My header</h1>
                <span id="slogan">my slogan</span>
            </div>
        </div>
    </div>
</header>

标题元素从正文的开头开始,距离窗口底部75 px。

header {
    height: calc(100vh - 75px);
}

当我开始向下滚动时,标题元素开始向上移动,标题和标语跨度。但是,我希望h1span元素垂直居中于标题元素的可见部分,有点像iStockPhoto website。请注意如何向下滚动搜索表单垂直居中到背景图像容器。

我如何实现类似的东西?

1 个答案:

答案 0 :(得分:0)

经过一些试验和错误后,我使用以下代码创建了效果。

<header>
  <div class="container">
    <div class="row" style="display: flex; justify-content: center">
      <div class="col-xs-12 text-center" style="align-self: center">
        <h1>Header</h1>
        <span id="slogan">my slogan</span>
      </div>
    </div>
  </div>
</header>

<section style="height: 1000px">
  <div class="container">
    <div class="row">
      <div class="col-xs-12">
        <p>Lorem ipsum dolor sit amet...</p>
      </div>
    </div>
  </div>
</section>

$(function() {
    var initialTitleHeight = $("header h1").position().top,
        initialSloganBottom = $("header span").position().top + $("header span").height(),
        headerHeight = $("header").height(),
        headerMaxMargin = headerHeight - (initialSloganBottom - initialTitleHeight + 50);

    $(window).scroll(function(event) {
        var scroll = $(window).scrollTop(),
            marginTop = (initialTitleHeight + scroll < headerMaxMargin) ? initialTitleHeight + scroll : headerMaxMargin;

        $("header h1").css({
            marginTop: marginTop + "px"
        });
    });
})

header {
    height: calc(100vh - 75px);
    background-color: #F90;

    .container, .row {
        height: 100%;
    }
}

您可以尝试here

相关问题