For graphs where you want to maintain the aspect ratio, use the padding-top

The principle of

To make the image equal to scale, you need to calculate the width and height of the image against a baseline. Padding-top, in %, represents the percentage of the width of the parent element. Based on this, when the height of an element is denoted as padding-top %, it is possible to display an element proportionally.

Equal scale display elements

For example, draw a rectangle with an aspect ratio of 1:2, set the width of the element to 10% of the parent element, and use the padding-top 20% of the element as its height. Codepen. IO/denghuijie /…

<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>

html,body{
  padding: 0;
  margin: 0;
  font-size: 0;
}
div{
  display: inline-block;
  padding-top: 40%;
  height: 0;
  background: red;
  width: 20%;
}
div:nth-child(3n+1){
  background: blue;
}
div:nth-child(3n+2){
  background: yellow;
}
Copy the code

Equal scale display width to height ratio

The aspect ratio of the image can be fixed by placing the image in an element of equal scale and using absolute positioning.

Codepen. IO/denghuijie /…

<div>
  <img src="//iconfont.alicdn.com/s/c30bea48-04a8-4114-84bb-bb84ecfd05ba_origin.svg" >
</div>
<div>
  <img src="//iconfont.alicdn.com/s/6fe16527-0a9e-4c49-abb9-3d23bf695a19_origin.svg" >
</div>
<div>
  <img src="//iconfont.alicdn.com/s/c0541005-51e3-4b43-bc48-99910d00965d_origin.svg" >
</div>
<div>
  <img src="//iconfont.alicdn.com/s/c0541005-51e3-4b43-bc48-99910d00965d_origin.svg" >
</div>
<div>
  <img src="//iconfont.alicdn.com/s/c0541005-51e3-4b43-bc48-99910d00965d_origin.svg" >
</div>

html,body{
  padding: 0;
  margin: 0;
  font-size: 0;
}
div{
  display: inline-block;
  position: relative;
  padding-top: 20%;
  height: 0;
  background: red;
  width: 20%;
}
div:nth-child(2n+1){
  background: blue;
}
img{
  position: absolute;
  width: 100%;
  height: auto;
  left: 0;
  top: 0; 
}
Copy the code

conclusion

The height of an element is expressed in units of padding-top %, which is the percentage of the width of the parent element. The width is expressed as a % ratio, which is the percentage of the width of the parent element. Thus, both the width and height of an element are expressed as a percentage of the width of the parent element. This keeps the element’s width-to-height ratio constant as the screen size changes.