【发布时间】:2020-01-12 03:14:49
【问题描述】:
一直在尝试似乎是一场艰苦的战斗。
我有一张图片,768 像素 x 411 像素。它必须被修复,因为它是 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;
}
【问题讨论】:
-
图片是否使用 HTML
元素显示?在这种情况下,根本不要设置
height;保持默认auto。 -
那行不通。它将渲染到高度为 0。在原始页面上它还说必须设置宽度和高度(来源:jennamolby.com/…)
标签: css