Signup/Sign In

How can I make a div not larger than its contents?

When we create a <div> element. It can be larger than the contents inside it. This <div> size can be adjusted using CSS property. Here are some ways to create a <div> not larger than its content.

Creating a div that fit its content using inline-block

Use display-inline: block to make div not larger than its contents. Here is an example that creates a div not larger than its element.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>HTML</title>
</head>
 <style>
   div {
     border: 2px solid black;
	 display: inline-block;
	 background-color: blue;
	 padding: 10px;
	 }
 </style>
<body>
    <h2> Div not larger than its content  </h2>
	<div>
    <p>The div container is used so that it is not larger than its contents. </p>
	</div>
</body>
</html>

Output

As we can see in the output that the div fits the contents.

div not larger than its contents

Using height and width property

There is yet another way to create a <div> not larger than its contents. Use width:fit-content and height: fit-content CSS property to <div>. Here is an example to create <div> not larger than its contents using height and width property.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>HTML</title>
</head>
 <style>
   div {
     border: 2px solid black;
	 width: fit-content;
     height: fit-content;
	 background-color: blue;
	 padding: 10px;
	 }
 </style>
<body>
    <h2> Div not larger than its content  </h2>
	<div>
    <p>The div container is used so that it is not larger than its contents. </p>
	</div>
</body>
</html>

Output

Here is the output showing the div perfectly fits its content.

div

Conclusion

Hence we can create a div not larger than its contents using CSS property. Either use the height or width property to resize the div element or use the inline-block property.