我知道我们可以使用 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>>);
在 CSS 中是否有标准的方法来做到这一点?
我知道使用 flexbox 和表格可以完成整个任务,但我想知道 CSS 是否提供了更简单的方法。 Flexbox、表格和简单的 Javascript 是可接受的替代方案。
最佳答案
您可以使用 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/