是否有 CSS 属性可以像 object-fit: "contains" 在 img 上那样重新缩放任何元素?

问题描述 投票:0回答:1

是否有 CSS 属性可以在窗口大小小于内容大小时缩小具有固定尺寸的 html 元素?

换句话说,内容应该缩小(并保持相同的比例)以适应新的窗口大小,就像属性 object-fit:“contain”对于替换元素所做的那样。

现在我编写了这个 JS 代码,它达到了我的预期,但我想知道它是否只能在 html/css 中完成?

这种方法的注意事项是您可能必须在计算中考虑边距和填充。

const CONTENT_WIDTH = 700;
const setContentScale = () => {
    const newScale = Math.min(window.innerWidth/ CONTENT_WIDTH, 1);
    const element = document.getElementById("container");
    if(element) {
        element.style.scale = newScale;
    }
}

setContentScale(); // <-- update scale on page load
window.onresize = () => setContentScale(); // <-- update on scale on windows resize
html css resize responsive scale
1个回答
0
投票

您可以使用 CSS 实现 JS 逻辑,但请务必检查浏览器支持。

调整下面屏幕的大小以查看结果:

@property --w {
  syntax: "<length>";
  inherits: true;
  initial-value: 90vw; /* the container width here (I am using the screen width for the demo */
}

.box {
  width: 600px; /* the element width */
  font-size: 20px;
  text-align: justify;
  border: 1px solid red;
  box-sizing: border-box;
  
  --s: tan(atan2(var(--w),1px)); /* uniteless value of the container width */
  scale: calc(var(--s)/600); /* container width dvided by element width */
  transform-origin: 0 0;
}
.box img {
  float: left;
  margin-right: 10px;
}

body {
  margin: 0;
}
<div class="box">
<img src="https://picsum.photos/id/1/150/150"> 
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam vulputate a sem at eleifend. Nam ut hendrerit ipsum. Maecenas felis urna, suscipit a posuere ut, rutrum vitae magna. Vivamus sagittis nisl dolor, in aliquam ipsum rutrum vitae. Nam consequat faucibus neque, vel rhoncus tellus mattis et. ipsum. Maecenas felis urna, suscipit a posuere ut, rutrum vitae magna. Vivamus sagittis nisl dolor, in aliquam ipsum rutrum vitae. Nam consequat faucibus neque, vel rhoncus tellus mattis et. a posuere ut, rutrum vitae magna. Vivamus sagittis nisl dolor, in aliquam ipsum rutrum vitae. Nam consequat faucibus neque, vel rhoncus tellus mattis et. 
</div>

© www.soinside.com 2019 - 2024. All rights reserved.