如何使用flexbox将flexbox行中图像的高度限制为可用空间?

时间:2015-12-01 14:51:31

标签: css flexbox

假设我有一个固定宽度和高度的容器,其中包含一个像这样的Flexbox:

    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let firstViewController = storyboard.instantiateViewControllerWithIdentifier("FirstViewController") as! FirstViewController
    self.presentViewController(firstViewController, animated: true, completion: {
        //This lines will be called after the view is loaded so the code will run
        firstViewController.firstButton.alpha = 0
    })
#somecontainer {
  background-color: gray;
  
  position: absolute;
  left: 70px;
  top: 50px;
  height: 400px;
  width: 400px;
}

#content {
  background-color: green;
  
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  
  padding: 2em;
  
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-content: stretch;
}

#content header {
  background-color: yellow;
  flex: 0 0 auto;
}

#content #imagecontainer {
  background-color: red;
  flex: 1 1 auto;
}

#content #descriptioncontainer {
  background-color: cyan;
  flex: 0 0 auto;
}

为了使浏览器减少第二个flex行中图像的高度到目前为止剩余内容适合Flexbox,我该怎么做?

1 个答案:

答案 0 :(得分:1)

我不确定你为什么绝对定位display:flex的项目,但一般来说,这两个属性不会混合所以我删除了大部分样式。

尽管如此,position:absolute是答案,但仅适用于图像。

我还删除了包含图像的不必要的额外div

#somecontainer {
  background-color: gray;
  height: 400px;
  width: 400px;
  display: flex;
  flex-direction: column;
}
#content {
  background-color: green;
  padding: 2em;
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-content: stretch;
}
#content header {
  background-color: yellow;
  flex: 0 0 auto;
}
#content #imagecontainer {
  background-color: red;
  flex: 1 1 auto;
  position: relative;
}
#content #imagecontainer img {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translateX(-50%) translateY(-50%);
  max-width: 100%;
  max-height: 100%;
}
#content #descriptioncontainer {
  background-color: cyan;
  flex: 0 0 auto;
}
<div id="somecontainer">
  <div id="content">
    <header>Title</header>
    <div id="imagecontainer">
      <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/9/9d/Tripod.svg/306px-Tripod.svg.png" alt="" />
    </div>
    <div id="descriptioncontainer">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea
      takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores
      et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</div>
  </div>
</div>