I\'m trying to create a horizontally scrollable div with flexbox. So far, I have most of it. However, the only problem I am facing is that I\'m trying to add space to my items,
There a few things you have to consider.
First of all; with justify-content
you define how remaining space is handled. By using space-between
your items will be aligned so that the space between them is equal, by setting it to center
the remaining space will be around all items, with all items stuck together.
In your case though, there is no remaining space, because your items actually stretch the div. So that doesn't help you.
Next; you've set the width of an item to 50%
. Which is fine, your item
's will be 50% of the viewport. That's because your grid will implicitly be 100% of the viewport. But because your image overflows the box, you can set margins if you want, and they will put the items further apart, but you need big-ass margins to actually see them. Bigger then the overflowing of your image.
So, to fix this, you make the images responsive by making them as width as the item;
.item img { display: block; height: auto; width: 100%; }
But that poses another problem; flexbox tries to size it's flex items to fit it all into the flex container. So you'll see that it automatically resizes your items so they will all fit in. To fix this, you have to explicitly force the width of your items;
.item { flex: 0 0 50%; }
Which is a shorthand for;
.item { flex-grow: 0; flex-shrink: 0; flex-basis: 50%; }
So basically you say; make my item 50% of it's container, and don't use your awesome algorithm to try to make it bigger or smaller.
Now you've got what you want, and you can use margin-right: 20px
for example to create a 20px space between your items.
Full snippet;
.grid { display: flex; width: 100%; }
.item { flex: 0 0 50%; margin-right: 20px; }
.item img { display: block; height: auto; width: 100%; }
.article-scroll-mobile {
box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
flex-wrap: nowrap;
text-align: center;
overflow-x: auto;
-webkit-overflow-scrolling: touch;
/*For iOS smooth scroll effect*/
}