How to Make Div Not Larger Than Its Contents

If you are looking to make your div not larger than its contents then you are at the right article. In this article, I am going to show you how you can set the limit of your div tags. This is one of the major problems which beginner’s face.

The major reason behind to minimise this up to its content is that when you are developing a multicolumn website then space matters a lot. The developer doesn’t want to waste the space which is covered by the block level elements.

Did you know: HTML Codes For Horizontal Lines

If you don’t get my point about Make Div Not Larger Than Its Contents. Then copy the below code and test in your browser.

Did you know: How To Disable Autocomplete HTML

In the above HTML code, I have used a div tag and change the background color into green two prominent space which dove has occupied. Inside the div tag, I have used a table and place 3 words to demonstrate the rows.

When you will execute the code in the browser you have observed that the background color is applied on the whole rows. As I have already mentioned that developers don’t want to waste the space, now we have to optimise that background to its content. We have to Limit as the width of the div tag. For this purpose, we will use inline-block as a value of display attribute.

Did you know: How To Change Element Class With JavaScript

In the following code, I am going to demonstrate inline-block.

Did you know: How To Remove Bullets in CSS

When you will execute the above code in your browser then you will observe that suddenly the area which is covered with the green background is not stretched to the content and its boundaries. Now we have optimised the space and limit as the div tag to its content.

There are many alternative attributes which we can use to minimise and optimise the space. Such as the inline value of the display attribute. In the following code, you will observe that we have used in line as a value of display it will work same as the above code.

Did you know: How To Disable TextArea Resize Property

Inline value of display will automatically adjust the width and height. So the best option to optimise the space is the inline value for display property.

SHARE