CSS flexbox:可变高度内容区域下方的可变高度页脚

时间:2019-01-01 16:02:30

标签: 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;我需要查看完整图像-这是用于照相馆。因此在这里裁剪并不是真正的选择。)

2 个答案:

答案 0 :(得分:1)

background-size: contain更改为background-size: cover

对我有用

答案 1 :(得分:1)

感谢@henryfhchan on Twitter提供解决方案! https://codepen.io/anon/pen/oJpvMZ

<div>
    <img src="...">
    <footer>caption is variable-size!</footer>
</div>

div {
  display: flex;
  flex-direction: column;
  height: 100vh;
}

img {
  display: block;
  max-width: 100%;
  object-fit: contain;
  flex: 0 1 auto;
  min-height: 0;  /* necessary */
}

footer {
  padding: 10px;
  flex: auto
}
相关问题