对于图片和视频元素,我们可以使用:width:100%; height:auto;
,甚至更好:object-fit:scale-down;
让图片自动缩放以适合其父级。
是否有任何类似(理想情况下仅限CSS)的方法以相同的方式缩放DOM元素,同时保持子元素之间的纵横比和视觉关系?
像transform:scale(width:100%);
这样的东西会像CSS属性一样完美。
答案 0 :(得分:0)
我不认为纯css是可能的,因为当浏览器调整大小时你需要重新计算父和子之间的比例(css不能这样做,因为它不是编程语言 - 只是一个样式) 。
jQuery解决方案如下:
function scale() {
$('.scaled').each(function() {
var scaled = $(this),
parent = scaled.parent(),
ratio = (parent.width() / scaled.width()),
padding = scaled.height() * ratio;
scaled.css({
'transform': 'scale(' + ratio + ')',
'transform-origin': 'top left'
});
parent.css('padding-top', padding); // keeps the parent height in ratio to child resize
})
}
scale();
$(window).resize(function() {
scale();
});

.test {
border: 1px solid red;
width: 30%;
position: relative;
}
.scaled {
/* needs to be positioned absolutey otherwise the parent takes the child original height */
position: absolute;
top: 0;
left: 0;
}
.scaled,
.not-scaled {
width: 500px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test">
<div class="scaled">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer feugiat quis magna in tempus. Vivamus magna metus, consequat at mollis sit amet, vulputate et eros. Phasellus ut mauris faucibus, ultrices mauris at, mollis eros. In hac habitasse platea
dictumst. Cras placerat pretium dui. Nullam quis lacinia nunc. Quisque est lectus, maximus at vehicula et, accumsan non nisi. Proin ac purus eget neque fermentum fringilla. Sed lectus mauris, pulvinar et venenatis ut, gravida quis nibh. Interdum et
malesuada fames ac ante ipsum primis in faucibus. In dapibus purus facilisis consequat aliquam. Donec mattis orci fermentum laoreet scelerisque. Aliquam pretium urna tortor, quis viverra lacus posuere eu. Maecenas posuere mauris in sapien gravida,
sed placerat purus efficitur.
</div>
</div>
<div class="not-scaled">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer feugiat quis magna in tempus. Vivamus magna metus, consequat at mollis sit amet, vulputate et eros. Phasellus ut mauris faucibus, ultrices mauris at, mollis eros. In hac habitasse platea
dictumst. Cras placerat pretium dui. Nullam quis lacinia nunc. Quisque est lectus, maximus at vehicula et, accumsan non nisi. Proin ac purus eget neque fermentum fringilla. Sed lectus mauris, pulvinar et venenatis ut, gravida quis nibh. Interdum et
malesuada fames ac ante ipsum primis in faucibus. In dapibus purus facilisis consequat aliquam. Donec mattis orci fermentum laoreet scelerisque. Aliquam pretium urna tortor, quis viverra lacus posuere eu. Maecenas posuere mauris in sapien gravida, sed
placerat purus efficitur.
</div>
&#13;