Open In App

How to set height equal to dynamic width (CSS fluid layout)?

Last Updated : 10 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

To set an element's height equal to its dynamic width in a CSS fluid layout, you can use the padding-bottom trick or the aspect-ratio property.

  • Padding-Bottom Trick: Set height: 0; and padding-bottom to a percentage relative to the width to achieve the desired aspect ratio.
  • Aspect-Ratio Property: Apply aspect-ratio: 1 / 1; to maintain a 1:1 ratio, ensuring height matches dynamic width.

Using Padding-Bottom Trick

To make an element's height equal to its dynamic width, you can use the padding-bottom trick in CSS.

Syntax:

.selector {
    padding-bottom: percentage or calc();
}
HTML
<html>
<head>
    <style>
        .square {
            width: 50%;
            height: 0;
            padding-bottom: 50%;
            background-color: lightblue;
        }
    </style>
</head>
<body>
    <div class="square"></div>
</body>

</html>


In this Example:

  • Width: The element's width is set to a percentage of its container, allowing it to be responsive.
  • Height: Setting the height to 0 ensures it doesn't contribute to the element's dimensions.
  • Padding-Bottom: By applying a percentage padding-bottom, the element's height becomes a proportion of its width. In this case, padding-bottom: 50% makes the height 50% of the width, resulting in a square aspect ratio.

Utilizing the aspect ratio

To make an element's height equal to its dynamic width, you can use the aspect-ratio property in CSS.

Syntax:

.selector {
    aspect-ratio: width/height;
}
HTML
<html >
<head>
    <style>
        .square {
            width: 50%; 
            aspect-ratio: 1 / 1; 
            background-color: lightblue; 
        }
    </style>
</head>
<body>
    <div class="square"></div>
</body>
</html>


In this Example:

  • Width: The element's width is set to a percentage of its container, allowing it to be responsive.
  • Aspect-Ratio: The aspect-ratio property defines the proportion between the element's width and height. Setting it to 1 / 1 ensures the height matches the width, creating a square.

    Next Article

    Similar Reads