html容器自定义宽高比,如何在保持宽高比的同时使用CSS自动调整DIV的大小?

小编典典

由于padding-*属性的百分比值是根据生成的框的包含块的宽度计算的,因此您可以:

添加一个虚拟元素,该元素不包含任何内容,但在垂直填充(padding-top或padding-bottom)中包含一个百分比,对应于所需的宽高比。

使用绝对定位可以从元素的正常流中删除所有内容,以防止它们增加高度。然后,使其生长以填充容器。

container {

position: relative;

width: 50%;

}

dummy {

padding-top: 75%; /4:3 aspect ratio/

}

element {

position: absolute;

top: 0;

bottom: 0;

left: 0;

right: 0;

background-color: silver;

}

some text

注意可以使用垂直边距代替垂直填充,但是会出现边距崩溃。为了防止这种情况,请添加

#container {

display: inline-block;

}

#container {

display: inline-block;

position: relative;

width: 50%;

}

#dummy {

margin-top: 75%; /* 4:3 aspect ratio */

}

#element {

position: absolute;

top: 0;

bottom: 0;

left: 0;

right: 0;

background-color: silver;

}

some text

使用::before伪元素,无需使用伪元素:

#container:before {

padding-top: 75%; /* 4:3 aspect ratio */

content: ''; /* Enable the pseudo-element */

display: block;

}

#container {

position: relative;

width: 50%;

}

#container:before {

padding-top: 75%; /* 4:3 aspect ratio */

content: ''; /* Enable the pseudo-element */

display: block;

}

#element {

position: absolute;

top: 0;

bottom: 0;

left: 0;

right: 0;

background-color: silver;

}

some text

2020-05-16

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值