An overview of the

Today I met a very interesting problem: “how to achieve a width adaptive, half the height of the width of the rectangle”.

After search engine screening and my own trial and error, I found that using padding-bottom was the perfect solution.

The solution

Padding-top /bottom and margin-top/bottom are both computed relative to the width of the parent element, and we can use this property to implement our requirements.

The code is as follows:

<div class="scale"></div>
Copy the code
.scale {
  width: 100%;
  height: 0;
  padding-bottom: 50%;
}
Copy the code

The key point here is height: 0; And padding – bottom: 50%; .

Since the padding is calculated based on the width of the parent element, the height becomes relative to the width of the parent element, and the height is set to 0 so that the padding is responsible for the height of the element.

The padding-bottom value is set to half the width value, so that the height is half the width.

To improve the

This is not enough because the height of the element is 0, which makes it impossible to set the height properly when there are children inside the element. So we need position: absolute; . The code is as follows:

<div class="scale">
    <div class="item">
So here's the container for all the child elements    </div>
</div>
Copy the code
.scale {
  width: 100%;
  padding-bottom: 56.25%;
  height: 0;
  position: relative; //
}  .item {  width: 100%;  height: 100%;  background-color: aquamarine;  position: absolute; // } Copy the code

Continue to improve

Now that we’ve solved the child element problem, let’s look at the element itself. At the beginning, we required an aspect ratio of 2:1, which was easier to achieve. But later, we wanted 16:9 aspect ratio, and the width was not 100%, so it was very troublesome to calculate the padding-bottom in this way. How to solve it?

In this case, we need to put another parent element in the outer layer and give the parent element control of the width.

The code is as follows:

<body>
    <div class="box">
        <div class="scale">
            <div class="item">
                item
 </div>  </div>  </div> </body> Copy the code
/* box is used to control width */
.box {
  width: 80%;
}
/* scale is used to achieve the width and height ratio */
.scale {  width: 100%;  padding-bottom: 56.25%;  height: 0;  position: relative; } /* item is used to place all child elements */ .item {  width: 100%;  height: 100%;  background-color: aquamarine;  position: absolute; } Copy the code

In this way, it can be solved perfectly.

The online demo

This article is formatted using MDNICE