所以我有一个页面,里面有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>
我想要的是让container
在body
居中,但将navbar
保持在顶部。
上面的代码将navbar
和container
对齐在中心。如何在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
.container
div,因此您可以为.navbar
提供一个absolute
position
,并使用 top
属性和适当的值(使用 CSS calc()
函数计算)将其移动到其正上方。
你可以给 .container 一个固定的宽度:
.container {
max-width: 860px;
margin-right: auto;
margin-left: auto;
}
body 设置为flex
容器的列,并使用 margin
进行.navbar
和.container
,而不是从 flex 父级justify-content
和align-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
可以应用于您的盒子以满足您的需求。