动态高度的CSS正方形 [英] CSS square with dynamic height
本文介绍了动态高度的CSS正方形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要做一个div
正方形. div
的高度是动态变化的,我希望宽度等于高度.我已经看到了很多解决方案,可以将 height 设置为等于 width (在伪元素上使用padding-bottom
),但是我需要另一种方法.纯CSS可以做到这一点吗?
I need to make a div
square. The height of the div
is dynamically changing and I want the width to be equal to the height. I have seen a lot of solutions to set the height to be equal to the width (with padding-bottom
on pseudo-elements), but I need it the other way arround. Is this possible with pure CSS?
推荐答案
不....嗯,这是一个技巧,其中一个使用隐藏的图像
No .... well, there is this trick, where one use a hidden image
div {
display: inline-block;
height: 170px;
background: red;
}
div img {
visibility: hidden;
height: 100%;
}
<div>
<img src="http://placehold.it/50">
</div>
已更新
这是一个脚本版本,也可以将其保持在宽度之内
And here is a script version, that also keep it within the width
堆栈片段
(function (d,t) {
window.addEventListener("resize", throttler, false);
window.addEventListener("load", throttler(), false); /* run once on load to init */
function throttler() {
if ( !t ) {
t = setTimeout(function() {
t = null;
keepSquared(d.querySelector('.container'),
d.querySelector('.squared'));
}, 66);
}
}
function keepSquared(co,el) {
var s = window.getComputedStyle(co, null);
var m = Math.min(
parseFloat(s.getPropertyValue("width")),
parseFloat(s.getPropertyValue("height")));
el.style.cssText =
'width: ' + m + 'px; height: ' + m + 'px;';
}
})(document,null);
html, body {
height: 100%;
margin: 0;
}
.container {
position: relative;
width: 50%;
height: 50%;
top: 50px;
left: 50px;
border: 1px solid black;
box-sizing: border-box;
}
.squared {
background-color: red;
}
<div class="container">
<div class="squared">
</div>
</div>
注意:自 resize
事件可以以高速率触发,使用调节器降低速率,这样处理程序就不会过于频繁地执行昂贵的操作,例如DOM修改.
这篇关于动态高度的CSS正方形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文