Method 1: Padding

  width: 50%;
  height: 0;
  padding-bottom: 25%;
Copy the code

The padding of an element, if the value is a percentage, is relative to the width of its parent element, and so is the padding-bottom.

Use padding-bottom instead of height to achieve height proportional to width. Set padding-bottom to the desired height. Also set its height to 0 so that the element’s “height” equals the padding-bottom value to achieve the desired effect.

Method two: VW, VH

  width: 50vw;
  height: 25vw;
Copy the code

According to CSS3 specification, viewport units mainly include the following four:

  • Vw: 1VW is equal to 1% of the viewport width
  • Vh: 1vh equals 1% of the viewport height
  • Vmin: Choose the smallest of vw and vH
  • Vmax: Pick the largest of vw and vH

Measured in viewport units, the viewport is 100vw wide and 100vh high.

For example, if the browser viewport size is 650px on the desktop, 1VW = 650 * 1% = 6.5px (this is a theoretical calculation, if the browser does not support 0.5px, then the actual render might be 7px.

The code is as follows:


      
<html>
<head>
  <meta charset="utf-8">
  <title></title>
  <link rel="stylesheet" href="https://cdn.bootcss.com/minireset.css/0.0.2/minireset.css">
<style>
body{
    display: flex;
    flex-direction:column;
    align-items: center;
}
.box1 {
  width: 50%;
  height: 0;
  padding-bottom: 25%;
  background: #f44336;
}
 
.box2 {
  width: 50vw;
  height: 25vw;
  background: #2196f3;
}
</style>  
</head>
<body>
    <div class="box1"></div>    <! --padding-->
    <div class="box2"></div>    <! --vw,vh-->
</div>
</body>
</html>

Copy the code