4 items – 25% each – with border & margin

So, I have searched through the internet and found problems that are a little alike but not exactly the same.

I have some sort of list that I want to show in a table form, and I want to use the whole width of the parent DIV it’s in (so 100%).
I want to show 4 items per line, and used something like thias:

ul.li{
 list-style-type: none;
 float: left;
 display: box;
 border: 1px solid black;
 margin: 5px;
 padding: 10px;
 width: 25%
}

You don’t have to be a mathematician to see what’s wrong here: 25% * 4 is 100, but plus the border & the margin, the total is over 100. So the outcome is only 3 list items per line, and a lot under the total width of the parent div.

I’ve tried using a table instead of list items, it’s a little easier to get the exact 100% width but it doesn’t work for the rest of my page since it’s not as flexible, it’s just not what I need.

I could place the border inside the box, and that solves the border problem, but I need the margin (whitespace) between the boxes of my list items.



1) box-sizing: border-box;, the width and height properties (and min/max properties) includes content, padding and border, but not the margin.

2) width: calc(25% – 10px); you use of margin:5px so must subtract 10px for (margin-left:5) and (margin-right:5) of width:25% .

ul li{
 box-sizing: border-box;
 list-style-type: none;
 border: 1px solid black;
 float: left;
 margin: 5px;
 padding: 10px;
 width: calc(25% - 10px);
}
ul li{
 box-sizing: border-box;
 list-style-type: none;
 border: 1px solid black;
 float: left;
 margin: 5px;
 padding: 10px;
 width: calc(25% - 10px);
}
<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
  <li>6</li>
  <li>7</li>
  <li>8</li>
</ul>

Try a calculated width: width: calc(25% – 30px)

You can use flex to solve it (I recommend you to read about it on css-tricks.com). What flex does is that it distrubute the items and take the margin in consideration. Basically you don’t even need to use width but use flex-basis. Using border-box (read about it) will calculate the padding + border you add to your li to the total width so it wont be, 25% + 20px but 25% including 20px, if that makes sense?

DEMO

<ul class="list">
  <li class="list__item">1</li>
  <li class="list__item">2</li>
  <li class="list__item">3</li>
  <li class="list__item">4</li>
</ul>

.list {
  display: flex;
  width: 100%;
  background-color: lightcoral;
  justify-content: center;
  align-content: center;
}

.list__item {
  list-style-type: none;
  box-sizing: border-box;
  display: block;
  border: 1px solid black;
  margin: 5px;
  padding: 10px;
  flex-basis: 25%
}