
Use one of these CSS recipes to set a div element’s width to fit its content.
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.
.my-div {
width: fit-content;
}
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.
.my-div {
display: inline-block;
}
Flex or grid items without a set width automatically size themselves to the width of their content.
.container {
display: flex; /* No width needed on the child div */
}
.container {
display: grid; /* No width needed on the child div */
}
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.
.my-div {
width: max-content;
}
© Copyright 2026 The Web Guy. All rights reserved.