0
votes

I want to have elements in a div box wrap and the next item should start where the previous one ends. At the same time, I want there to be a gap between each items. However there should be no gap between the items and the container boundary. I have setup an example here

https://codepen.io/sneaky666/pen/yLJZGJo

#A {
  font-size:0;
  width:200px;
  border:1px solid black;
}
#A > div {
  display:inline-block;
  background-color:orange;
  color:white;
  padding:10px;
  font-size:14px;
  margin:0 10px 10px 0;
}
<div id="A">
  <div>Item 1</div>
  <div>Item 2 Test</div>
  <div>Item 3 Test Test</div>
  <div>Item 4 Test</div>
  <div>Item 5 Test</div>
</div>

My attempt:

By making it display inline blocks, it achieves the wrapping effect. Also it causes the element to start where the previous one ends (if it were a traditional grid, then it aligns the elements with the axises causing extra space which I don't want).

Then to create the gap between the items, I use a margin right and bottom of 10px. The problem here is that for the items on the last row and the last item on each column, it puts a 10px margin around it which touches the container boundary. I want to avoid that. CSS grid grid-gap allows to get around it, but it creates the extra space around items to align them with the axis.

Does anyone know how to fix this?

Thanks

1
It's not clear what you mean by "start where the previous ends", could you elaborate on that? Also it would be loads more helpful if you could crudely draw the desired result instead of describing it.Robo Mop

1 Answers

0
votes
  1. if you can use display:flex, than
#A {
   display: flex;
   justify-content: space-between;
}

no margin needed for #A children, justify-content: space-between will keep space between elements in same row, and no space between element and it's containers noundry.

2.or you could make #A text-align:justify, because #A children's display is inline-block, it will work as well, it will treat #A's children as text, and will justify it along the line

#A {
  text-align: justify
}

No margin for spacing needed between children