AI solution for CSS coding question on BFE.dev
10. golden-ratio rectangle
To create a golden-ratio rectangle, we can use the ::before
pseudo-element to set a percentage-based height that keeps the ratio of width and height constant.
.golden-ratio {
background-color: #ccc;
position: relative;
}
.golden-ratio::before {
content: "";
display: block;
padding-bottom: 61.8%;
}
Here, we set the padding-bottom of the ::before
pseudo-element to 61.8% which is the decimal approximation of the golden ratio (1.618).
The position: relative
property is added to the parent element to make sure that the ::before
pseudo-element is positioned relative to its parent.
Notice that we haven't set the width of the .golden-ratio
element. This is because the width will be determined by the padding-bottom value we set in the ::before
pseudo-element. The padding-bottom will create a box with a constant aspect ratio, independent of the width of the parent element.
We could define a width for the .golden-ratio
element, but it wouldn't impact the aspect ratio, only the size of the box.
.golden-ratio {
background-color: #ccc;
position: relative;
width: 400px;
}
.golden-ratio::before {
content: "";
display: block;
padding-bottom: 61.8%;
}
This CSS would make the .golden-ratio
element 400px wide, but the aspect ratio would remain constant at 1.618.