I am working on a layout using HTML and CSS with Flexbox. My goal is to display 4 items in each row. However, my current code only displays 3 items per row. I would appreciate any guidance on how to fix this issue.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Flexbox Layout</title>
<style>
.container {
display: flex;
flex-wrap: wrap;
gap: 8px;
border: 4px solid gray;
}
.element {
width: 25%;
height: 300px;
padding: 8px;
box-sizing: border-box;
background-color: silver;
}
</style>
</head>
<body>
<div class="container">
<div class="element"></div>
<div class="element"></div>
<div class="element"></div>
<div class="element"></div>
<div class="element"></div>
<div class="element"></div>
</div>
</body>
</html>
Despite setting the .element
width to 25%, which should allow for 4 items per row, the items are displaying as 3 per row.
Why are the items not displaying 4 per row as expected? How can I adjust my CSS to ensure 4 items per row?
Thank you in advance for your assistance!
1
In Flexbox gap
is not accounted for when setting widths so you have to adjust the widths to take the gaps into account.
There will be 3 gaps so we have to divide the extra 3 gaps but the 4 items in the row.
.container {
display: flex;
flex-wrap: wrap;
gap: 8px;
border: 4px solid gray;
}
.element {
width: calc(25% - (8px * (3 / 4)));
height: 100px;
padding: 8px;
box-sizing: border-box;
background-color: silver;
}
<div class="container">
<div class="element"></div>
<div class="element"></div>
<div class="element"></div>
<div class="element"></div>
<div class="element"></div>
<div class="element"></div>
</div>
Your thought seems to be correct. In this case though you need to consider the gap between your elements
.
Change the width to calc(25% - 8px)
to remove the gap from the width, and it will do the trick. Hope that helps.
.container {
display: flex;
flex-wrap: wrap;
gap: 8px;
border: 4px solid gray;
}
.element {
width: calc(25% - 8px);
height: 300px;
padding: 8px;
box-sizing: border-box;
background-color: silver;
}
<div class="container">
<div class="element"></div>
<div class="element"></div>
<div class="element"></div>
<div class="element"></div>
<div class="element"></div>
<div class="element"></div>
</div>