我使用 flex
将 2 个 div
居中,我想在页面底部添加第三个 div
。就像下图一样
(我不希望前 2 个 div
因为第三个 div
而向上移动。我希望前 2 个 div
是以其父项为中心。)
我试过了,但是第三个 div
被推到了屏幕之外。而且我不能使 #centerWrapper 的高度
小于 100%
,因为这样 2 个 div
就不会在整个页面上居中。
JSFiddle
*,
*:before,
*:after {
margin: 0;
padding: 0;
box-sizing: border-box;
}
html,
body,
#parent {
width: 100%;
height: 100%;
}
#centerWrapper {
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
}
#centerWrapper * {
width: 100px;
height: 100px;
}
#firstChild {
background-color: brown;
}
#secondChild {
background-color: lightblue;
}
#thirdChild {
background-color: greenyellow;
}
<div id="parent">
<div id="centerWrapper">
<div id="firstChild"></div>
<div id="secondChild"></div>
</div>
<div id="thirdChild"></div>
</div>
最佳答案
更新
将两个 block 都保持在这样指定的位置不需要 flexbox 的灵 active 。 position
可能是更好的解决方案。将此规则集添加到 #centerWrapper
:
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
对于 #thirdChild
,添加这些样式以使其保持在视口(viewport)底部。
position: absolute;
bottom: 0;
使 #parent
成为 #centerWrapper
和 #thirdChild
的 flex 容器。
片段
*,
*:before,
*:after {
margin: 0;
padding: 0;
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
}
#parent {
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
flex-wrap: nowrap;
align-items: center;
background: yellow;
overflow-y: visible;
}
#centerWrapper {
width: 100px;
height: 200px;
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
#centerWrapper * {
min-width: 100px;
min-height: 100px;
}
#firstChild {
background-color: brown;
}
#secondChild {
background-color: lightblue;
}
#thirdChild {
min-width: 100px;
min-height: 100px;
background-color: greenyellow;
position: absolute;
bottom:0;
}
<div id="parent">
<div id="centerWrapper">
<div id="firstChild"></div>
<div id="secondChild"></div>
</div>
<div id="thirdChild"></div>
</div>
关于html - 将元素添加到页面底部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39279395/