Open In App

How to stretch div to fit the container ?

Last Updated : 15 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

Stretching a child div to fit the full width and height of its parent container can be achieved through various CSS methods. Here are two effective methods to accomplish this:

Method 1: Using 100% Width and Height

This is the most simple approach. By setting the width and height properties of the child div to 100%, it will automatically stretch to fill the entire width and height of the parent container.

Example: In this example, we are using the above-explained method.

HTML
<!DOCTYPE html>
<html lang="en">
<head>
    <style>
        .container {
            height: 400px;
            background-color: green;
        }

        .num1 {
            background-color: yellow;
            height: 100%;
            width: 100%;
        }
    </style>

</head>

<body>
    <div class="container">
        <div class="num1">
            Welcome to GFG.
        </div>
    </div>
</body>
</html>

Output:

Method 2: Using Table Display Properties

This method involves setting the parent container to display: table and the child container to display: table-row. This technique allows the child div to stretch and fit the parent container.

Example: In this example, we use the above-explained method.

HTML
<!DOCTYPE html>
<html lang="en">

<head>
    <style>
        .container {
            height: 200px;
            background-color: green;
            display: table;
            width: 100%;
        }
        
        .num1 {
            background-color: greenyellow;
            display: table-row;
        }
    </style>
</head>

<body>
    <div class="container">
        <div class="num1">
            Welcome to GFG.
        </div>
    </div>
</body>

</html>

Output:

Alternative Modern Method: Flexbox

A more modern and flexible method to make a child div stretch to fit its parent container is using CSS Flexbox. This method allows for more control and flexibility in layout design.

HTML
<!DOCTYPE html>
<html lang="en">
<head>
    <style>
        .container {
            height: 400px; /* Set a fixed height for the container */
            background-color: green;
            display: flex; /* Enable flexbox layout */
            justify-content: center;
            align-items: center;
        }
 
        .num1 {
            background-color: yellow;
            flex: 1;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="num1">
            Welcome to GFG.
        </div>
    </div>
</body>
</html>

Output:

Screenshot-2024-09-15-163213
Alternative Modern Method: Flexbox



How to stretch div to fit the container ?
Next Article

Similar Reads