html - flexbox 中超出父 div 的水平边距

标签 html css sass flexbox

我在使用 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: centerouter 上和 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/

相关文章:

html - 适合对象 : cover with percentages

css - 我可以在 SASS mixin 中声明一个新变量吗?

bootstrap-4 - Bootstrap 4.6.0 form-validation-states 不会改变验证边框的颜色

javascript - 如何在javascript中将html表格转换为字符串

javascript - 应用悬停鼠标时 Accordion 不会停止

html - css 格式问题与顶部的 html

ember.js - 将 Material Design 组件与 ember-cli-sass 结合使用

html - 如何最好地制作具有多个页面的 Web 应用程序?

php - 在所有输入都填满之前,如何停止重新加载页面?

html - CSS、HTML 和背景颜色问题。