Set Div Width with CSS

How To Set Div Width To Fit Its Content

|

3 CSS Div Width Recipes

Use one of these CSS recipes to set a div element’s width to fit its content.

Use The “width: fit-content;” Selector

This is the cleanest, semantically direct, most modern way to handle it. The div just sizes itself to whatever’s inside, but it won’t blow past its container—basically works like max-content but with a width limit baked in.

Example CSS:

.my-div {
width: fit-content;
}


Use The “display: inline-block;” Selector

Using the display: inline-block selector makes the div act like an inline element horizontally (so it only takes up the space it needs for its contents width), but you still get all the block-level stuff like vertical margins and padding.

Example CSS:

.my-div {
  display: inline-block;
}

Use The “display: flex;” Or The “display: grid;” Selectors

Flex or grid items without a set width automatically size themselves to the width of their content.

Example Flex CSS:

.container {
  display: flex; /* No width needed on the child div */
}

Example Grid CSS:

.container {
display: grid; /* No width needed on the child div */
}


Use The “width: max-content;” Selector

Using width: max-content; selector forces the element to be as wide as it needs to be so nothing overflows—basically it stops text from wrapping and makes the div as wide as the longest line or word.

Example CSS:

.my-div {
  width: max-content;
}

Leave a Reply

Your email address will not be published. Required fields are marked *

    © Copyright 2026 The Web Guy. All rights reserved.

    Subscribe

    Get access to exclusive content and receive The Web Guy Newsletter.
    The Web Guy Logo-Box Black