html - 设置 div 高度以填充剩余高度

标签 html css

我正在制作卡片 View 。这里显示的是一个极度简化的形式。
我无法让 .main div 在悬停时自动扩展以填充剩余的垂直空间。

我在 StackOverflow 上找到的一种方法是使用绝对定位。我对它不是很挑剔,但是当我需要更改时,比如说,描述的字体大小,我也必须更改 bottom 边界,否则会有重叠.

是否有解决方法或 CSS 属性(在本例中为高度)来执行此操作?
任何不需要 .foot div 高度的东西?

div.wrapper {
  position: absolute;
  top: 0;
  left: 0;
  width: 240px;
  height: 200px;
  color: #171812;
  background: #a0a0a0;
  border-radius: 5px;
  transition: 0.2s;
}

.wrapper:hover {
  height: 250px;
}

.head {
  width: 100%;
  padding: 10px 20px;
}

.main {
  height: 100px;      /*<<<< HERE*/
  background: #f00;   /*for development purpose*/
}

img {
  height: 100%;
  display: block;
  margin: 10px auto;
}

.foot {
  position: absolute;
  left: 0;
  bottom: 0;
  padding: 10px 20px;
}
<div class="wrapper">
  <div class="head">Name</div>
  <div class="main">
    <img src="http://i.imgur.com/w5U482j.jpg" />
  </div>
  <div class="foot">
    Description
  </div>
</div>

最佳答案

您可以使用 flex 来完成,关注flex-grow属性(property)。此外,您不需要使用 position: absolute这里:

body {
    margin: 0;
}

.wrapper {
    display: flex;
    flex-direction: column;
    width: 240px;
    height: 200px;
    color: #171812;
    background: #a0a0a0;
    border-radius: 5px;
    transition: 0.2s;
}

.wrapper:hover {
    height: 250px;
}

.head {
    padding: 10px 20px;
}

.main {
    flex-grow: 1;
    height: 100px;
    background: #f00;
}

img {
    height: calc(100% - 20px);
    display: block;
    margin: 10px auto;
}

.foot {
    padding: 10px 20px;
}
<div class="wrapper">
    <div class="head">Name</div>
    <div class="main">
        <img src="http://i.imgur.com/w5U482j.jpg"/>
    </div>
    <div class="foot">Description</div>
</div>

JSFiddle

关于html - 设置 div 高度以填充剩余高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42454203/

相关文章:

html - 使用任何必要的方式使 DIV 居中

html - 在页脚中使用背景色覆盖背景图像

javascript - iScroll获取父Div的高度

html - 试图防止图像溢出

html - CSS3 变换属性不适用于响应式导航栏

css - 如何将 text + input 放置在 2 列中,中间垂直对齐

jquery - 滚动时如何更改导航栏内容?

javascript - 如何在 HTML 中使用 JavaScript 创建圆形、正方形或三 Angular 形?

html - 保持所有 LI 的边框高度相同

html - 如何对 Google 机器人和其他机器人隐藏某些 DIV