How to Set a Flex Container to Match the Width of Its Flex Items?
Last Updated :
03 Oct, 2024
Flexbox is a powerful layout model in CSS that simplifies the process of designing responsive layouts. One common scenario is needing the flex container to dynamically adjust its width to match the combined width of its flex items. By default, flex containers expand to fill the available space, but with the right techniques, we can ensure that the container's width is determined solely by its flex items.
We can set a flex container to be the width of its flex items by the methods below.
1. Using inline-flex
One of the simplest solutions to this issue is to use the inline-flex value instead of flex for the display property. While flex creates a block-level container that stretches to the full width of its parent, inline-flex creates an inline-level flex container that only occupies as much space as its content requires.
.flex-container {
display: inline-flex;
border: 1px solid black;
}
Example: With inline flex, the flex container will only take up the width of its flex items, adjusting dynamically as the number or size of items changes.
HTML
<!--index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Inline Flex Example</title>
<style>
.flex-container {
display: inline-flex;
border: 1px solid black;
}
.flex-item {
padding: 10px;
background-color: lightblue;
border: 1px solid blue;
}
</style>
</head>
<body>
<div class="flex-container">
<div class="flex-item">Item 1</div>
<div class="flex-item">Item 2</div>
<div class="flex-item">Item 3</div>
</div>
</body>
</html>
Output: The container will now shrink to fit the width of its flex items, rather than stretching to fill the entire width of the page.
Using inline-flex2. Using width: max-content
Another way to ensure that the flex container is only as wide as its content is by setting the container's width to max-content. This CSS value tells the container to size itself based on the maximum width of its contents (i.e., the width of the flex items).
.flex-container {
display: flex;
width: max-content;
border: 1px solid black;
}
Example: In this case, the container will stretch to fit its content exactly and will not extend beyond the width of its flex items.
HTML
<!--index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Max Content Flex Example</title>
<style>
.flex-container {
display: flex;
width: max-content;
border: 1px solid black;
}
.flex-item {
padding: 10px;
background-color: lightcoral;
border: 1px solid red;
}
</style>
</head>
<body>
<div class="flex-container">
<div class="flex-item">Item A</div>
<div class="flex-item">Item B</div>
<div class="flex-item">Item C</div>
</div>
</body>
</html>
Output:
Using width: max-content