小编典典
由于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