How to make a div not larger than its contents
Overview
The div tag defines a division or a section in an HTML document that is used as a container to hold other HTML elements. It occupies more space than its contents and looks larger than its contents. We can make a div that is not larger than its contents using the following two CSS properties:
display:inline-block
display:table
If we apply any one of the above CSS properties to div tag, then the div will not be larger than its contents.
Example
Explanation
In the HTML tab:
- Line 6: We create a
divtag namedcontent1. - Line 8: We create a
divtag namedcontent2. - Line 10: We create a
divtag namedcontent3.
In the CSS tab:
- Lines 1–3: We add a
background-colorproperty forcontent1. - Lines 5–8: We add a
background-coloranddisplay: inline-blockproperty. - Lines 9–12: We add a
background-coloranddisplay: tableproperty.
We apply background color to all three div tags so that we can distinguish the space they use.
We can observe from the output that the first div is larger than its contents. However, the div tags which have CSS properties applied to them perfectly encapsulate their contents with no extra space.