如何在不居中导航栏的情况下垂直居中body元素



所以我有一个页面,里面有navbar和一堆内容。代码大纲如下:

.container {
  display: flex;
  justify-content: center;
  align-items: center;
}
<div class="navbar">
<!-- Various navbar links here -->
</div>
<div class="container">
<!-- Some content here -->
</div>

我想要的是让containerbody居中,但将navbar保持在顶部。

上面的代码将navbarcontainer对齐在中心。如何在body中垂直居中container并防止navbar居中?

你可以

这样做:

html, body {height: 100%} /* mandatory */
body {margin: 0} /* mandatory */
body {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
.navbar {
  position: absolute;
  top: calc(50% - 150px); /* moved down by 50% of the screen height - half of the container's height - navbar's height */
  width: 1200px;
  max-width: 100%;
  height: 50px;
  background: Khaki;
}
.container {
  width: 1200px;
  max-width: 100%;
  height: 200px;
  background: Lavender;
}
<div class="navbar">
<!-- Various navbar links here -->
</div>
<div class="container">
<!-- Some content here -->
</div>

body元素应该变成带有flex-direction: column柔性容器,以便它垂直堆叠其项目。由于您只想center .containerdiv,因此您可以为.navbar提供一个absolute position,并使用 top 属性和适当的(使用 CSS calc() 函数计算)将其移动到其正上方。

你可以给 .container 一个固定的宽度:

.container {
max-width: 860px;
margin-right: auto;
margin-left: auto;
}
您可以将

body 设置为flex容器的列,并使用 margin 进行.navbar.container,而不是从 flex 父级justify-contentalign-items

所需的基本代码:

html,
body {
  height: 100%;
  margin: 0;
}
body {
  display: flex;
  flex-direction: column;
}
.navbar {
  margin: 0 auto;
}
.container {
  margin: auto;
}
<div class="navbar">navbar
</div>
<div class="container">
  container
</div>

(分钟-)width(分钟-)height可以应用于您的盒子以满足您的需求。

最新更新