如何将用户屏幕宽度的CSS变量放入calc函数?

我的网站是在较大的显示器上设计的,屏幕宽度为2560px(三星32英寸)。因此,必须按比例缩小它才能在任何较小的屏幕上正常显示;例如,一台17英寸屏幕的普通笔记本电脑像素宽度为1366像素。因此,通过除以1366/2560,我们得到了在CSS transform:scale(calc(1366 / 2560));公式中使用的.53正确比例比例。

整个页面都包裹在一个我称为.omniScale的div中

.omniScale {
    display: table; 
    margin:0 auto;
    transform-origin: top left;
    transform:scale(calc(1366 / 2560));
}

这很好用,但是1366必须在页面加载时动态更改为用户设备的宽度,而不管它是平板电脑,笔记本电脑,中型台式显示器还是更大的显示器(无论是大电视)。

使用100vw而不是硬接线号不起作用。我不想使用JavaScript(如果可以避免的话),所以必须对那些已关闭js的人起作用。

wing_wx 回答:如何将用户屏幕宽度的CSS变量放入calc函数?

我认为这不是正确的方法。为了使所有屏幕都响应,最好使用百分比和@madia

有关更多信息:https://blog.froont.com/9-basic-principles-of-responsive-web-design/

示例:

.container {
    width: 2560px;
}

@media only screen and (max-width: 2560px) {
    .container {
        width: 1366px;
    }
}

@media only screen and (max-width: 1366px) {
    .container {
        width: 900px;
    }
}

@media only screen and (max-width: 900px) {
    .container {
        width: 500px;
    }
}
,

欢迎使用堆栈溢出:]

遗憾的是,目前没有机制可以计算纯CSS中两个 length 值的整数比率calc(100vw / 2560px)不起作用,因为您可以只能将长度除以整数以获得其他长度,而不是除以其他长度以获得整数。

因此,如果要获取参考元素与实际视口的比率,则JavaScript似乎是唯一的选择。合理的方法是使用JS来设置CSS自定义属性,然后由样式完成其余工作:

function setScaleRatio() {
  viewportWidth = document.documentElement.clientWidth;
  fullWidth = 2560 + 200;
  // (2560 is reference size,+200 just to make sure we'll see right border in this example)
  scaleRatio = viewportWidth / fullWidth;
  document.documentElement.style.setProperty('--ratio',scaleRatio);
};
setScaleRatio();
window.addEventListener('resize',setScaleRatio);
[style]::before {
  content: attr(style);
}
<div style="
width: 2560px;
transform: scale(var(--ratio));
transform-origin: top left;
font-size: 100px;
background-color: black;
color: white;
"></div>

本文链接:https://www.f2er.com/2710119.html

大家都在问