我在使用 flex 时边距出现一些意外行为,我希望得到一些帮助来理解原因。
我有一些像这样的简单 html:
<div className="dashboard">
<div className="dashboard__inner-container">Inner Container</div>
</div>
我的 scss 文件是这样的:
.dashboard {
text-align: center;
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
flex: 1 1 auto;
background-color: #f4f6f8;
}
.dashboard__inner-container {
display: flex;
flex-direction: column;
background-color: #ffffff;
flex: 1 1 auto;
width: 100%;
margin: 100px 50px;
}
我期望的是内部容器将完全填满父容器,顶部和底部减去 100px,左右减去 50px。垂直边距按预期工作,但水平边距实际上延伸到父 div 之外,因此内部容器看起来仍然占据了父 div 的整个宽度。
我不确定这是否与 flexbox 相关。
这是一个独立的 CodePen https://codepen.io/MaxMillington2/pen/EQWZoj
最佳答案
使用 align-items: center
时与 column
方向,该元素将折叠到其内容宽度,而不是其默认值 stretch
, 这使得它填充其父级的宽度。
此外,当设置 width: 100%
时到 inner
, 它将覆盖默认值 stretch
,这将使该元素成为父级宽度 + 边距的 100%。
对于预期的输出,删除 align-items: center
在 outer
上和 width: 100%
在 inner
.
堆栈片段
html {
height: 100%;
overflow: auto;
}
.outer {
display: flex;
justify-content: center;
flex-direction: column;
background-color: #f4f6f8;
height: 100%;
}
.inner {
display: flex;
flex-direction: column;
background-color: #ffffff;
flex: 1 1 auto;
text-align: center;
margin: 100px 80px;
}
<div class='outer'>
outer
<div class='inner'>
inner
</div>
</div>
关于html - flexbox 中超出父 div 的水平边距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48711203/