变换比例使缩放元素周围保持原始空间 [英] transform scale keeps the original space around the scaled element
问题描述
我有两个嵌套的div。 内一个
是转换:scale(0.5)
。
I have two nested divs. The inner one
is transform: scale(0.5)
.
两者都是显示:inline-block;
。
我需要做的是外部div
将其宽度调整为内部div的宽度。那就是我应该发生的,但事实并非如此。发生的情况是外部div认为内部div具有其原始大小。
What I need to happen is the outer div
fits it's width to the width of the inner one. That's what I supposed to happen but not. What occur is that the outer div «thinks» the inner div has it's original size.
仅当内部div为<时,外部div才适合其宽度。 code> transform:scale(1),但不使用小于1的比例因子,例如: 0.5
(请参见示例)。
The outer div fits it's width to the inner's width only if the inner div is transform: scale(1)
but not using an scale factor less than 1, for example: 0.5
(see example).
我需要一些方法来通过CSS优雅地实现这一目标。
I need some way to achieve this by CSS in an elegant way.
这里有代码:
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
.red { background-color: #f00; }
.green { background-color: #0f0; }
.box_1, .box_2 {
display: inline-block;
}
.box_1 {
width: 300px;
height: 300px;
transform: scale(0.5);
transform-origin: left top;
}
</style>
</head>
<body>
<div class="box_2 green">
<div class="box_1 red">Hello World</div>
</div>
</body>
</html>
在这里您可以预览:
在这里有一个实时示例: https://jsfiddle.net/0bc4sxk3/
Here you have a live example: https://jsfiddle.net/0bc4sxk3/
关于如何解决此问题的任何想法?
Any idea on how to solve this?
推荐答案
一种残酷的方法是实际上减少元素所需的空间。
A brutal way would be to virtually reduce space needed by element.
您的示例显示了一个已知的宽度和高度,因此很容易。
Your example shows a known width & height, so it makes it easy. else you would need a javascript method.
.box_1 {
width: 300px;
height: 300px;
transform: scale(0.5);
transform-origin: left top;
margin-bottom:-150px;
margin-right:-150px;
}
https://jsfiddle.net/0bc4sxk3/1/
扩大规模将意味着积极的利润。
Scaling up would mean positive margins.
仅在屏幕上进行转换,元素仍使用文档流中所需的初始空间。
Transform only happens at screen, elements still use initial room and place needed in the flow of the document.
这篇关于变换比例使缩放元素周围保持原始空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!