Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

html
communitycreator

How to make a div not larger than its contents

Gutha Vamsi Krishna

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 div tag named content1.
  • Line 8: We create a div tag named content2.
  • Line 10: We create a div tag named content3.

In the CSS tab:

  • Lines 1–3: We add a background-color property for content1.
  • Lines 5–8: We add a background-color and display: inline-block property.
  • Lines 9–12: We add a background-color and display: table property.

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.

RELATED TAGS

html
communitycreator
RELATED COURSES

View all Courses

Keep Exploring