Open In App

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

Improve
Improve
Like Article
Like
Save
Share
Report

To create a fluid layout in CSS, set an element’s height to the same value as its dynamic width. This makes the layout more adaptable and responsive since the element’s height will automatically change depending on the viewport’s width. It is possible to determine the element’s height by using the padding by setting the height attribute to 0. Using a percentage of the width or computation, the padding-bottom property may be used to set an element’s height.

Approaches: There are several ways to implement a fluid layout with CSS. The two most typical ones are as follows:

Using utilizing padding: As seen in the syntax above, setting the padding-bottom property to a percentage of the width or a calculation might result in a fluid height for the element.

 

Syntax:

.selector {
    height: 0;
    padding-bottom: percentage or calc();
}

 Example: Using Padding.

HTML




<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" 
          content="width=device-width, 
                   initial-scale=1.0">
    <title>Document</title>
  
    <!-- here is the styling part -->
    <style>
        .container {
            width: 80px;
            margin: auto;
        }
  
        .box {
            height: 0;
            padding-bottom: 100%;
            background-color: #f2caca;
        }
    </style>
</head>
  
<body>
    <div class="container">
        <div class="box"></div>
    </div>
</body>
</html>


Output:

The output of the above HTML code.

Utilizing the aspect ratio: A fluid layout may also be made by using the aspect ratio of an element. As a result, the height is set to 0, and the aspect ratio attribute is used to keep the element’s aspect ratio constant.

Syntax:

.selector {
    height: 0;
    aspect-ratio: width/height;
}

Example: Using Aspect-Ratio

HTML




<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" 
          content="IE=edge">
    <meta name="viewport" 
          content="width=device-width, 
                   initial-scale=1.0">
    <title>Document</title>
  
    <style>
        .container {
            background-color: red;
            width: 100px;
            /* 1:1 Aspect Ratio */
            padding-top: 100px;
            /* If you want text inside of it */
            position: relative;
        }
  
        .box {
            height: 0;
            aspect-ratio: 0.5;
            background-color: black;
        }
    </style>
</head>
  
<body>
    <div class="container">
        <div class="box"></div>
    </div>
</body>
</html>


Output:

Using Aspect-ratio



Last Updated : 27 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads