css - 根据其内容调整 flex 元素的大小

标签 css flexbox

抱歉,另一个 flexbox 相关问题 :)

我有两个 flex 元素:

  • 包含居中 div(黄色)的容器(红色)
  • 未定义高度的页脚(蓝色)

红色容器有一个 flex-grow:1 属性,强制它占用屏幕上的剩余空间

enter image description here

当黄色元素大于屏幕尺寸时会出现此问题。我希望我的红色容器根据其内容增长。知道我该怎么做吗?

enter image description here

HTML:

<div class="container">
    <div class="content"></div>
</div>
<div class="footer"></div>

CSS:

body,
html {
    margin: 0;
    height: 100%;
    display: flex;
    flex-direction: column;
}

.container {
    flex-grow: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    background: red;
}

.content {
    background: yellow;
    height: 2000px;
    width: 100px;
}

.footer {
    flex-shrink: 0;
    height: 50px;
    background-color: blue;
}

https://codepen.io/stepinsight/pen/roRVGQ

== 编辑 ==

Andre 帮助我找到了答案,非常感谢! 在上面的代码中,您唯一需要更改的是将 height 替换为 min-height 并将 % 替换为 vh 用于 body/html 标签 🎉

body,
html {
    margin: 0;
    min-height: 100vh;
    display: flex;
    flex-direction: column;
}

最佳答案

只需删除 body 元素上的 height 属性并在 html 中添加 height: 100%

* { box-sizing: border-box; }

html { 
  height: 100% 
}

body {  
  display: flex;
  flex-direction: column;
  margin: 0;
  padding: 0; 
}

.container {
  display: flex;
  align-items: center;
  justify-content: center;
  background: red;
}

.content {
  background: yellow;
  height: 2000px;
  width: 100px;
}

.footer {
  height: 50px;
  background-color: blue;
}

更正:https://codepen.io/ferreirandre/pen/maoVvb

随意调整 .content 的高度

关于css - 根据其内容调整 flex 元素的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54201878/

相关文章:

css - 是否可以在 flex 布局中定位每行的第一个和最后一个元素?

html - 电子邮件模板链接颜色不会改变

jquery - 修复显示隐藏 block

jquery - 关于实现类似 map 的导航界面的建议?

css - Flexbox: flex 增长问题

html - 在 CSS 中嵌套 Flexbox

html - 按百分比更改图像高度不起作用

html - 菜单固定在顶部,滚动事件上有动画

css - 使用 bootstrap 3 让页脚粘在底部

javascript - scrollreveal.js 和 flexbox