在我的页面中间,我有一个div元素,里面有一些内容(其他div,图像,什么的)。
<div>
before
</div>
<div id="content-to-scale">
<div>something inside</div>
<div>another something</div>
</div>
<div>
after
</div>
我想缩放这个元素(内容到规模)和它的所有子元素。似乎是CSS3变换规模运作的工作。然而,问题是这只是对元素层次结构的可视化的转换,它并不改变元素在页面上的空间量(或位置)。换句话说,将该元素缩放得更大会导致它与“before”和“after”文本重叠。
有没有一种简单/可靠的方法不仅可以缩放视觉表示,还可以缩放占用的空间量?
没有JavaScript的纯CSS加分。甚至更多的点,解决方案做正确的事情与其他转换函数,如旋转和倾斜。这并不一定要使用CSS3转换,但它确实需要跨最近所有支持HTML5的浏览器来支持。
HTML(谢谢Rory)
<!DOCTYPE html>
<html>
<head>
<meta name="description" content="Sandbox for Stack Overflow question http://stackoverflow.com/q/10627306/578288" />
<meta charset=utf-8 />
<title>Sandbox for SO question about scaling an element both visually and dimensionally</title>
</head>
<body>
<div id="wrapper">
<div class="surrounding-content">
before
</div>
<div id="content-to-scale">
<div>something inside</div>
<div><img src="http://placekitten.com/g/150/100"></div>
<div>another something</div>
</div>
<div class="surrounding-content">
after
</div>
</div>
</body>
</html>
CSS(还是从罗里的基地开始的)
body {
font-size: 13px;
background-color: #fff;
}
#wrapper {
width: 50%;
margin-left: auto;
margin-right: auto;
border: 0.07692307692307693em solid #888;
padding: 1.1538461538461537em;
}
.surrounding-content {
border: 0.07692307692307693em solid #eee;
}
#content-to-scale {
border: 0.07692307692307693em solid #bbb;
width: 10em;
}
#content-to-scale {
font-size: 1.1em;
}
#content-to-scale img {
width: auto;
height: auto;
min-width: 100%;
max-width: 100%;
}
解释:
我使用字体大小和ems来“缩放”子元素的尺寸。
Ems是与当前上下文的字体大小相关的维度单位。
因此,如果我说我的字体大小为13px,边框为1(所需的边框宽度,以像素为单位)除以13(当前上下文的字体大小,也以像素为单位)=0.07692307692307693em,浏览器应该呈现1px的边框
为了模拟15px的填充,我使用了相同的公式,(期望的像素)/(当前上下文的字体大小(以像素为单位)=期望的EMS。15/13=1.1538461538461537 EM
为了控制图像的缩放,我使用了我最喜欢的一种缩放方式:自然比例保持缩放,让我解释一下:
图像有一个自然的高度和宽度,以及它们之间的比率。如果宽度和高度都设置为“自动”,大多数浏览器将保留此比率。然后,您可以使用min-width和max-width控制所需的宽度,在本例中,使其始终缩放到父元素的全宽,即使它将缩放到其自然宽度之外。
(您也可以使用max-width和max-height 100%来防止图像超出父元素的边框,但绝不能缩放超出它们的自然尺寸)
这样做确实有一些缺点:ems中嵌套的字体大小是间接应用的。意思是如果你有:
<style type="text/css">
div{
font-size: 16px;
}
span{
font-size: 0.5em;
}
</style>
<div>
<span>
<span>
Text
</span>
</span>
</div>
您将以4px而不是您可能预期的8px呈现“文本”。