How to make div not larger than its contents using CSS?

Given a div and the task is to set div not larger then its content. If the size of content change then the size of div also change.

Method 1: Use display: inline-block property to set a div size according to its content.

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
    <head>
        <style>
            .geeks {
                background-color: green;
                color:white;
                display: inline-block;
            }
        </style>
    </head>
      
    <body>
        <div class = "geeks">
            Welcome to GeeksforGeeks!
        </div>
    </body>
</html>    

chevron_right


Output:

Method 2: This method set the width and height property to fit-content value.

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
    <head>
        <style>
            .geeks {
                background-color: green;
                color:white;
                width:fit-content;
                height:fit-content;
            }
        </style>
    </head>
      
    <body>
        <div class = "geeks">
            Welcome to GeeksforGeeks!
        </div>
    </body>
</html>                    

chevron_right


Output:



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.