How to Make an HTML <div> Element not Larger Than its Content

In his tutorial, we will show you how to make the size of the <div> element not larger than its content. If the size of the content changes, the size of the <div> will change as well.

It is quite easy if you follow the steps described below.

Let’s see an example and try to discuss each part of the code together.

Create HTML

  • Use a <div> element with the class "box".
  • Place the <h2> tag in the <div> and write some content in it.
<body>
  <div class="box">
    <h2>Welcome to W3docs!</h2>
  </div>
</body>

Add CSS

  • Choose colors for your text and background using the background-color and color properties.
  • Add the display property to specify the type of the box used for an HTML element. The display property has many values. We use the "inline-block" value.
  • Use the padding property which creates space around the element's content.
.box {
  background-color: #54bbff;
  color: white;
  display: inline-block;
  padding: 10px;
}

Here is the result of our code.

Example of making a <div> not larger than its content using the display property with the "inline-block" value:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the documnet</title>
    <style>
      .box {
        background-color: #54bbff;
        color: white;
        display: inline-block;
        padding: 10px;
      }
    </style>
  </head>
  <body>
    <div class="box">
      <h2>Welcome to W3docs!</h2>
    </div>
  </body>
</html>

Result

Welcome to W3docs!

Let’s see another example.

Example of making a <div> not larger than its content using the height and width properties:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      .box {
        background-color: #54bbff;
        color: white;
        width: fit-content;
        height: fit-content;
        padding: 7px;
      }
    </style>
  </head>
  <body>
    <div class="box">
      <h2>Welcome to W3docs!</h2>
    </div>
  </body>
</html>

In the example above, we set the width and height properties to the "fit-content" value.

Example of making a <div> not larger than its content using the display property with the "inline-flex" value:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      .box {
        display: inline-flex;
        background-color: #8ebf42;
        color: white;
        padding: 15px;
      }
    </style>
  </head>
  <body>
    <div class="box">
      <h2>Welcome to W3docs!</h2>
    </div>
  </body>
</html>

In this example, we use the display property with the "inline-flex" value which displays an element as an inline-level flex container.

Do you find this helpful?

Related articles