CSS最小/最大高度基于内容和容器的高度

时间:2018-08-21 22:27:18

标签: css angular

我正在Angular中设计一个可重用的组件,其中的一种预期用途是将其放置在<td>中的<table>内。提前,我不知道没有该组件的行高度将是多少,并且组件本身可以根据其内容以可变的高度进行渲染。我面临的核心问题是组件的高度需要足够大才能有用,但不能太大。决策树如下所示:

if component height <= row height without component, show full height
if component height > row height without component, set max-height

仅使用min-heightmax-height会遇到以下问题:

.c1 {
  max-height: 5rem;
  min-height: 3rem;
  overflow-y: auto;
}

.h1 {
  height: 2rem;
}
.h1:before {
  content: '2rem';
}

.h2 {
  height: 4rem;
}
.h2:before {
  content: '4rem';
}

.h3 {
  height: 6rem;
}
.h3:before {
  content: '6rem';
}

.h4 {
  height: 8rem;
}
.h4:before {
  content: '8rem';
}

.red {
  color: white;
  background-color: red;
}

.blue {
  color: white;
  background-color: blue;
}

table {
  border-collapse: collapse;
}
td {
  border: 1px solid black;
  width: 10rem;
  padding: 0;
}
<table>
  <tr>
    <td>Not good, blue doesn't need to be 3rem high</td>
    <td>
      <div class="red h1"></div>
    </td>
    <td>
      <div class="c1">
        <div class="blue h1"></div>
      </div>
    </td>
  </tr>
  <tr>
    <td>Everything is good here</td>
    <td>
      <div class="red h1"></div>
    </td>
    <td>
      <div class="c1">
        <div class="blue h2"></div>
      </div>
    </td>
  </tr>
  <tr>
    <td>Everything is good here</td>
    <td>
      <div class="red h2"></div>
    </td>
    <td>
      <div class="c1">
        <div class="blue h2"></div>
      </div>
    </td>
  </tr>
  <tr>
    <td>Everything is good here, allowing height to grow, but not too much</td>
    <td>
      <div class="red h2"></div>
    </td>
    <td>
      <div class="c1">
        <div class="blue h4"></div>
      </div>
    </td>
  </tr>
  <tr>
    <td>Everything is good here, Blue is showing the full 4rem height</td>
    <td>
      <div class="red h3"></div>
    </td>
    <td>
      <div class="c1">
        <div class="blue h2"></div>
      </div>
    </td>
  </tr>
  <tr>
    <td>Not good, Blue could show the full 6rem height here</td>
    <td>
      <div class="red h4"></div>
    </td>
    <td>
      <div class="c1">
        <div class="blue h3"></div>
      </div>
    </td>
  </tr>
</table>

我需要的是将最大高度设置为max(x, rowHeightWithoutElement)的方法,其中x是组件的最小可用高度。在代码中有一种繁琐而痛苦的方法(渲染隐藏组件的行,检查行高,计算适当的最大高度,设置最大高度,显示元素;对行进行任何更改均重复)。我想知道的是,是否有一个纯CSS解决方案,或者是一个不需要每次更改都不断查询DOM的混合解决方案。我希望答案是“否”,但我认为值得CSS专家询问。

我知道CSS最小/最大函数可能会解决此问题,并且它们是为CSS Level 4提出的,但这还有很长的路要走。

0 个答案:

没有答案
相关问题