Calc() 像素高度动态基于动态宽度和 CSS 比率



一直在尝试一场看似艰苦的战斗。

我有一张图片,768px x 411px。它必须被修复,因为它是javascript刮刮乐游戏的一部分。虽然可以调整它的大小,但它必须具有固定值。

我的想法是将宽度设置为 100vw,然后计算图像的纵横比,然后以该比率为基础,从当前图像宽度值计算高度。

我一直在阅读很多,但到目前为止没有运气。仅使用 CSS 就不可能做到这一点吗?这是我代码的一部分:

:root{
--defaultWidth: 768px;
--defaultHeight: 411px;
--widthMain: calc(100% - 5px);                 
--perspective: calc( var(--defaultHeight) / var(--defaultWidth) );
}
.scratchpad {
width: var(--widthMain);
height: calc( var(--widthMain) * var(--perspective) );
/* also tried variations of this
height: calc( calc(var(--widthMain) * var(--perspective)) ); */
}
.scratch-container {
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
width:100%;
}

谢谢。

编辑: 不能说我很自豪,但我通过将它与 PHP 混合而将自己入侵到临时解决方案中

<?php
// Calling getimagesize() function 
list($width, $height) = getimagesize("cover.png");
$ratio   =  $height/$width;
?>
<style type="text/css">
:root{
--defaultWidth: <?=$width?>px;
--defaultHeight: <?=$height?>px;
--widthMain: calc(100vw - 15px);                 
--perspective: calc( var(--defaultHeight) / var(--defaultWidth) );
}
html {
box-sizing: border-box;
}
*, *:before, *:after {
box-sizing: inherit;
}
.scratchpad {
width: var(--widthMain);
height: calc((100vw - 15px) * <?= $ratio; ?> );
border: solid 2px #fff;
margin: 0 auto;
}

您可以通过利用padding-toppadding-top在使用相对单位时引用父宽度的事实(例如,50% 是父宽度的一半(来做到这一点:

.container-a {
width: 180px;
}
.container-b {
width: 100px;
}
.image-wrapper {
position: relative;
/* Image aspect ratio as a percentage */
padding-bottom: 50%;
}

img {
position: absolute;
width: 100%;
height: 100%;
}
<div class="container-a">
<div class="image-wrapper">
<img src="//placehold.it/200x100" />
</div>
</div>
<br />
<div class="container-b">
<div class="image-wrapper">
<img src="//placehold.it/200x100" />
</div>
</div>

查看图像如何调整大小,但它和.image-wrapper元素保持正确的纵横比?

最新更新