首页 > 解决方案 > CSS flexbox:可变高度内容区域下方的可变高度页脚

问题描述

我需要做一个简单的布局,顶部区域是可变大小的图像,底部区域应该是可变高度的页脚,页脚的内容是

到目前为止我最好的尝试:

* { padding: 0; margin: 0; }

html, body {
  height: 100%;
  min-height: 100%;
}

.body {
  display: flex;
  min-height: 100%;
}

nav {
  width: 150px;
  flex-shrink: 0;
  background-color: gray;
}

main {
  flex-grow: 1;
	display: flex;
	flex-direction: column;
}

.image {
  flex-grow: 1;
  border: 1px solid blue;
  
  background-image: url('https://www.hawaiimagazine.com/sites/default/files/field/image/plumeria%202%20Eric%20Tessmer%20Flickr.jpg');
	background-size: contain;
	background-repeat: no-repeat;
	background-position: top center;
}

footer {
  border: 1px solid red;
}
<div class="body">
  <nav>side nav</nav>
  <main>
    <div class="image"></div>
    <footer>
      I need this to stay directly below the image but not go beneath the fold
    </footer>
  </main>
</div>

(水平和垂直调整预览窗口的大小,您会看到即使图像没有填充高度,页脚也不会升高来填充它。)

我尝试了许多不同的方法,包括不使用 flexbox、使用网格和使用<img>标签——最后任何一种都可以。(只是没有 JS ......)我几乎在<img>标签和使用方面取得了成功,object-fit: contain但它会将页脚推到折叠下方。

编辑:在这里更新尝试(虽然仍然没有解决):

* { padding: 0; margin: 0; }

html, body {
  height: 100%;
  min-height: 100%;
}

.body {
  display: flex;
  min-height: 100%;
}

nav {
  width: 150px;
  flex-shrink: 0;
  background-color: gray;
}

main {
  flex-grow: 1;
	display: flex;
	flex-direction: column;
}

img {
  max-width: 100%;
	max-height: 80vh;
  object-fit: contain;
}

footer {
  height: 20vh;
  border: 1px solid red;
}
<div class="body">
  <nav>side nav</nav>
  <main>
    <img src="https://www.hawaiimagazine.com/sites/default/files/field/image/plumeria%202%20Eric%20Tessmer%20Flickr.jpg">
    <footer>
      I need this to stay directly below the image but not go beneath the fold.<br>
      UPDATED ATTEMPT: This footer is now fixed-height. If possible I'd like to avoid this.
    </footer>
  </main>
</div>

(此示例显示页脚位于内容下方,但现在页脚是固定高度的,这是不可取的)

我们如何使用纯 CSS 使页脚的内容保持在图像下方,同时在图像很高时不延伸到折叠下方?

(编辑:我应该澄清一下,我确实将尺寸设置为contain故意;我需要查看完整的图像——它是用于照片库的。所以在这里裁剪并不是一个真正的选择。)

标签: cssflexbox

解决方案


更改background-size: containbackground-size: cover

它对我有用


推荐阅读