I’m trying to align a set of items across multiple rows in a container. Each item has a different width, and I want the layout to automatically adjust to fit the items neatly, filling each row as much as possible before wrapping to the next row. The maximum allowed items per row is 4.
The width of each item should be equal with the content width. The last item in row should have the width to be able to cover the rest of the space even if the content is not long.
.container {
display: flex;
flex-wrap: wrap; /* Allows items to wrap to the next row */
width: 100%;
max-width: 1200px;
}
.item {
background-color: #3498db;
color: white;
margin: 10px;
padding: 20px;
box-sizing: border-box;
flex: 1 1 calc(25% - 20px); /* 4 items per row */
text-align: left;
border-radius: 5px;
width: fit-content;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Responsive Layout</title>
</head>
<body>
<div class="container">
<div class="item">Item 1 data is here, plrase askjd sadsad asd </div>
<div class="item">Item 2</div>
<div class="item">Item 2</div>
<div class="item">Item 2</div>
<div class="item">Item 2adm </div>
<div class="item">Item 2 san. asmd. sada sdndsa m sad </div>
</div>
</body>
</html>
In my situation the item with text Item 2adm
should have the width equal with the content and the last item should fill the rest of the space, but in my scenario the width is 50/50.
How can I achieve the expected result?
2