我知道我可以使用padding-top / bottom
制作一个宽度很高的元素#element {
width: 40%;
padding-top: 40%;
}
上述原因之所以如此,是因为,当给予填充顶部/底部一个百分比值时,它相对于父级的宽度,而不是高度。
我怎么能做同样的事情,只是把它变得宽而不是反过来?
它需要响应,解决方案应该适用于所有主流浏览器,包括IE8 +
答案 0 :(得分:1)
好吧,我找到了一个独特的黑客,虽然这只是一个半答案(它可能会回答某些情况)。也许拥有更多智慧的人可以扩展它并找到完整的解决方案。 : - )
基于< img>的事实标签仅在缩放一个尺寸时保留其比例,我将一个嵌入1x1垫片的测试组合在一起,并将其缩放以适合高度。
它运作良好。遗憾的是,缺点是图像需要包含在一个元素中,该元素是生成高度的内容的兄弟,并且包含内容的实际元素的宽度不会改变。
因此,如果您能够复制内容,它实际上可能会有效。
Here's a JSFiddle来证明这一点。而且,这是评论代码:
<style type="text/css">
#outer {
position:relative; /* limit the absolutely positioned #box */
}
#box {
background-color:red;
position:absolute;
height:100%; /* make this box fill the height of #outer */
display:block;
z-index:-1; /* put it behind the content box generating height (maybe not if you want to hide / copy it) */
}
img {
height:100%; /* generate the proportional square */
}
#inner {
position:absolute;
top:0; bottom:0; left:0; right:0; /* make the inner box just fill the box generated by the image */
}
.centered {
text-align:center;
margin-top:50%;
transform:translateY(-50%); /* quick vertical-centering css */
}
#box-text {
color:white;
}
#height-box {
display:inline-block; /* make the box width fit to the content - not vital either way */
}
</style>
<div id="outer">
<div id="box">
<img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7">
<div id="inner">
<p id="box-text" class="centered">Box</p>
</div>
</div>
<div id="height-box" contenteditable="true">is<br>this<br>actually<br>possible?</div>
</div>
答案 1 :(得分:0)
您可能需要javascript 使用jquery它应该是这样的:
$('#element').css({
width: + $('#element').height()
})
但上面的内容非常粗糙,我甚至没有测试过它
更新它有效 - 看我的小提琴: fiddle for above
或者我认为如果您愿意,我可能会有点草率:
var el=$('#element');
el.css({
width: + el.height()
});
答案 2 :(得分:0)
来自here:
<div class='box'>
<div class='content'>Aspect ratio of 1:1</div>
</div>
.box{
position: relative;
width: 50%; /* desired width */
}
.box:before{
content: "";
display: block;
padding-top: 100%; /* initial ratio of 1:1*/
}
.content{
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
}