javascript - 为一个元素设置长度(高度或宽度)减去另一个元素的可变长度,即 calc(x - y),其中 y 未知

标签 javascript jquery css flexbox

我知道我们可以使用 calc定义长度时:

flex-basis: calc(33.33% - 60px);
left: calc(50% - 25px);
height: calc(100em/5);

但是如果长度是可变的呢?

height: calc(100% - <<header with variable height>>);

width: calc(100% - 50px - <<box with variable width>>);

enter image description here

在 CSS 中是否有标准的方法来做到这一点?

我知道使用 flexbox 和表格可以完成整个任务,但我想知道 CSS 是否提供了更简单的方法。 Flexbox、表格和简单的 Javascript 是可接受的替代方案。

height demo

width demo

最佳答案

您可以使用 CSS 表格:

.wrapper {
  display: table;
  width: 100%;
  margin: 15px 0;
}

.horizontal.wrapper > div {
  display: table-cell;
  white-space: nowrap; /* Prevent line wrapping */
  border: 1px solid;
}
.left { width: 100px } /* Minimum width of 100px */
.center { width: 0; }  /* Width given by contents */

.vertical.wrapper { height: 200px; }
.vertical.wrapper > div {
  display: table-row;
}
.vertical.wrapper > div > span {
  display: table-cell;
  border: 1px solid;
}
.top    { height: 100px; } /* Minimum heigth of 100px */
.middle { height: 0; }     /* Height given by content */
.bottom { height: 100%; }  /* As tall as possible */
<div class="horizontal wrapper">
  <div class="left">100px wide</div>
  <div class="center">Auto width, given by contents</div>
  <div class="right">Remaining space</div>
</div>
<div class="vertical wrapper">
  <div class="top"><span>100px tall</span></div>
  <div class="middle"><span>Auto height, given by contents</span></div>
  <div class="bottom"><span>Remaining space</span></div>
</div>

水平的情况下也可以用float来实现:

#wrapper, .right { overflow: hidden; } /* Establish BFC */
#wrapper > div { border: 1px solid; }
.left, .middle { float: left; }
.left { width: 100px }
<div id="wrapper">
  <div class="left">100px</div>
  <div class="middle">Auto width, given by contents</div>
  <div class="right">Remaining space</div>
</div>

关于javascript - 为一个元素设置长度(高度或宽度)减去另一个元素的可变长度,即 calc(x - y),其中 y 未知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33129660/

相关文章:

javascript - 整页js将下一节滑过当前

javascript - .string之后的所有字符如何大写。像手机键盘

html - 限制CSS中的文本区域

jquery - 过滤后提交所有表单数据

html - 悬停在 CSS 中不改变颜色属性

滚动时CSS使侧边栏固定但悬停在顶部时可滚动

javascript - 谷歌图表显示法国数字值?

javascript - React Native 进度 View iOS 不重新渲染

javascript - 显示文件的内容

javascript - 如何在 Google Analytics 的自定义变量中使用变量