核心就是:
width: 100%;
height: 0;
padding-bottom: 50%;
这样可以保证子元素的高度是父元素的宽度的一半。
不管是margin还是padding,给他们设置 top、right、bottom、left 的值的时候,如果取值是百分比的形式,这个百分比都是相对于父元素的宽度来取值的。
<!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><metahttp-equiv="X-UA-Compatible"content="IE=edge"><metaname="viewport"content="width=device-width, initial-scale=1.0"><title>Document</title><style>* {margin: 0;padding: 0;}html,body {height: 100%;}.outer {width: 400px;height: 100%;display: flex;align-items: center;background-color: pink;margin: auto;}.inner {width: 100%;height: 0;/* 高度是父元素宽度的一半 */padding-bottom: 50%;background-color: orange;position: relative;}.box {position: absolute;width: 100%;height: 100%;display: flex;align-items: center;justify-content: center;}</style></head><body><divclass="outer"><divclass="inner"><divclass="box">test</div></div></div></body></html>
