【问题标题】:Centering content in an element, and also locking a navbar to the bottom (Use a flexbox?How?)将元素中的内容居中,并将导航栏锁定在底部(使用 flexbox?如何?)
【发布时间】:2014-03-20 13:01:58
【问题描述】:

我正在尝试设置一个登陆欢迎页面,该页面将填充用户浏览器的整个视口。我希望在其上方有一些居中的内容,可能是一些文本或某种幻灯片。我以前将内容居中,这不是真正的问题。我还需要将导航栏固定到元素的底部。我不能使用绝对定位,因为当我滚动过去时我需要它贴在窗口顶部。我试过用 flexbox 来做这件事,但遇到了很多问题。首先是导航栏是从中间开始的,其次是居中的内容不在中间,它似乎稍微偏右。

这是我正在使用的 css:

html, body {
    width: 100%;
    height: 100%;
}

.navbar {
    margin-bottom: 0;
    width: 100vw;
}

.full-size {
    height: 100vh;
}

#page-welcome {
    background: url(http://placekitten.com/1920/1080);
    -moz-background-size: cover;
    -o-background-size: cover;
    -webkit-background-size: cover;
    background-size: cover;
}

.align {
    display: flex;
    justify-content:center;
    align-items: center;
    height:100%;
}
.align > .end{
    align-self:flex-end;
}
.align > .top{
    align-self:flex-start;
}

我还有一个 CodePen 可以在这里演示我的问题: http://codepen.io/anon/pen/GCpzE

【问题讨论】:

  • 不是每个浏览器都能理解 vh/vw 单位,尤其是移动浏览器。最好提供某种回退,否则一切都会被压扁。

标签: html css twitter-bootstrap flexbox


【解决方案1】:

默认情况下,方向设置为,但你需要的是

http://codepen.io/cimmanon/pen/bCDfL

html, body {
  width: 100%;
  height: 100%;
}

.navbar {
  margin-bottom: 0;
  width: 100vw;
}

.full-size {
  height: 100%;
  height: 100vh;
}

#page-welcome {
  background: url(http://placekitten.com/1920/1080);
  -moz-background-size: cover;
  -o-background-size: cover;
  -webkit-background-size: cover;
  background-size: cover;
}

.align {
  display: -webkit-flex;
  display: flex;
  -webkit-flex-direction: column;
  flex-direction: column;
  -webkit-justify-content: space-between;
  justify-content: space-between;
  -webkit-align-items: center;
  align-items: center;
  height: 100%;
}

我在演示中添加了一个额外的元素,以便您可以看到它将垂直居中(尽管它与完美居中的接近程度取决于其他元素的高度)。

【讨论】:

  • 感谢您的帮助,您已经解决了我的导航栏问题,但现在我不会在没有 h1 的情况下将 foo div 垂直居中。我可能遗漏了一些东西,我对使用 css 处理这种类型的东西很陌生,通常只使用 js。
  • 这就是你可以用 Flexbox 做的所有事情。你不能只在中间有一个项目,在底部有一个项目,除非底部的项目是绝对定位的,或者你为中间的项目使用嵌套的 flex 容器,或者你在顶部有一个不可见的元素。跨度>
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-02-25
  • 1970-01-01
  • 1970-01-01
  • 2019-11-29
  • 1970-01-01
  • 2017-06-29
  • 1970-01-01
相关资源
最近更新 更多