我想要这样的东西:
height: calc(width + 5px);
这只是一个小例子,但我最终想要一种方法来使用设置宽度作为计算的一部分,而不是一种更简单的方法来解决这个例子。我做的任何搜索都给出了如何使用calc()
设置宽度的示例。谢谢!
您可以使用纯CSS最接近的是将CSS变量与calc
相结合
:root {
--width: 100px;
}
div {
border: 1px solid red;
height: calc(var(--width) + 5px);
width: var(--width);
}
<div>
test
</div>
这将允许您定义CSS变量--width
并使用它来计算div的新高度。
如果宽度设置为px,则可以使用相同的值来计算高度。 如果以百分比(%)设置,这可能会有所帮助:
.container {
width: 20%;
/* set the same percent as width in padding top of a container. */
padding-top: calc(20% + 5px);
background-color: aqua;
position: relative;
}
/* This is the box where it is done. Because all the space in the container is padding,
you must to set this box as `absolute` and fill the container with
width and height set to 100% */
.box {
width: 100%;
height: 100%;
position: absolute;
top: 0;
}
<div class="container">
<div class="box">
</div>
</div>
希望它能满足您的需求..