How to adopt a flex div's width to content in HTML?

By default, flex containers with display: flex take up the full width of their parent. To make a flex container shrink to fit its content, use display: inline-flex.

The Problem with display: flex

Regular flex containers expand to fill their parent's width, even when content is smaller:

<!DOCTYPE html>
<html>
<head>
<style>
.flex-container {
    display: flex;
    padding: 10px;
    background-color: lightblue;
    border: 2px solid blue;
    margin: 10px 0;
}
</style>
</head>
<body>

<div class="flex-container">
    <span>Short content</span>
</div>

</body>
</html>

Solution: Using display: inline-flex

The inline-flex value makes the container shrink to fit its content width:

<!DOCTYPE html>
<html>
<head>
<style>
.inline-flex-container {
    display: inline-flex;
    padding: 10px;
    background-color: lightgreen;
    border: 2px solid green;
    margin: 10px 0;
}

.flex-item {
    padding: 5px;
    background-color: white;
    margin: 2px;
}
</style>
</head>
<body>

<div class="inline-flex-container">
    <div class="flex-item">Item 1</div>
    <div class="flex-item">Item 2</div>
</div>

</body>
</html>

Complete Example with Comparison

<!DOCTYPE html>
<html>
<head>
<style>
.flex-full {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    max-width: 200px;
    padding: 10px;
    margin: 20px 0;
    background-color: lightcoral;
    border: 2px solid red;
}

.flex-content {
    display: inline-flex;
    flex-direction: row;
    flex-wrap: wrap;
    max-width: 200px;
    padding: 10px;
    margin: 20px 0;
    background-color: lightblue;
    border: 2px solid blue;
}

.item {
    padding: 8px;
    background-color: white;
    margin: 2px;
    border: 1px solid gray;
}
</style>
</head>
<body>

<h3>display: flex (full width)</h3>
<div class="flex-full">
    <div class="item">A</div>
    <div class="item">B</div>
</div>

<h3>display: inline-flex (content width)</h3>
<div class="flex-content">
    <div class="item">A</div>
    <div class="item">B</div>
</div>

</body>
</html>

Key Differences

Property display: flex display: inline-flex
Container Width Full parent width Shrinks to content
Block Behavior Block-level Inline-level
Flexbox Features All supported All supported

Conclusion

Use display: inline-flex when you want a flex container that shrinks to fit its content width instead of expanding to fill the parent. All flexbox properties work the same way with both values.

Updated on: 2026-03-15T23:18:59+05:30

355 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements