<分区>
我尝试制作的是随屏幕大小而变化的正方形。
所以我将宽度设置为 25%。 如何确保高度与宽度保持相同的长度(以像素为单位)?
提前致谢。
标签 javascript css html
<分区>
我尝试制作的是随屏幕大小而变化的正方形。
所以我将宽度设置为 25%。 如何确保高度与宽度保持相同的长度(以像素为单位)?
提前致谢。
最佳答案
你可以使用顶部/底部 padding
以百分比表示的属性,以实现结果。
.box {
width: 25%;
padding-bottom: 25%;
}
A percentage value在顶部/底部 padding
或 margins
是相对于框的包含 block 的宽度。
<percentage>
The percentage is calculated with respect to the width of the generated box's containing block, even for 'padding-top' and 'padding-bottom'.
由于盒子的高度会随着内容的增加而增加,我们可以用元素包裹内容 .wrapper
并相对于盒子绝对定位,然后使用 top
, right
, left
和 bottom
填充框的整个空间的属性。
<div class="box">
<div class="wrapper">
<!-- content goes here... -->
</div>
</div>
.box {
width: 25%;
position: relative;
}
.box:after {
content: "";
display: block;
padding-top: 100%; /* 1:1 square */
}
.box > .wrapper {
position: absolute;
top: 0; right: 0; bottom: 0; left: 0;
}
更多信息您可以引用my answer here (响应式容器部分)。
关于javascript - 以 % 为单位的 CSS 宽度和以 px 为单位的高度,两者的长度相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22507231/