CSS如何根据高度缩放和宽高比宽度?

时间:2020-05-11 02:19:35

标签: html css

假设高度是父级div的80%,我希望宽度是高度的两倍。所以我可以这样做:

.scal { 高度:“ 80%”, 宽:2 x高 }

有可能还是我有另一种方法来实现这一目标?

2 个答案:

答案 0 :(得分:1)

如果您知道父元素的高度,我想您要问的内容可以在CSS中实现

CSS

width: calc(whateverElementsHeightInUnits * 2)

但是我认为最好的方法是使用jQuery,如下所示

jQuery

$(window).resize(function(){
   $('.scal').css({ width: $(whateverElement).innerHeight() * 2 });
});

答案 1 :(得分:1)

您可以使用CSS custom properties (variables)calc函数的组合来解决此问题:

:root {
  --rect-height: 100px;
}

.rect {
  background: red;
  display: block;
  height: var(--rect-height);
  width: calc(var(--rect-height) * 2);
}
<div class="rect"></div>