I'm trying to create some kind of universal component of flex container. This component consists of container and its children in a row.
If there are too many children in a line, those who don't have enough space go to second line. It can be easily achieved with flexbox, but also I want to be able to set gutter between elements. And first and last elements of a line shouldn't have left and right margin respectively.
I do this using negative margin technique, but the problem here is that right margin can provoke overflow issues if container is too big. I can solve this problem adding overflow: hidden
to cut off negative margin, but it provokes problem with overflowing items inside container (drop-downs, etc).
So now I'm looking for silver bullet, implementation which can satisfy this requirements:
- There are multiple items in a row. Width of items can differ.
- If some items have not enough space, they go to next line.
- There is a gap between items (margin), and first and last item doesn't have left and right margin, respectively.
- Inside container can be placed overflowing content (drop-downs), so I can't use
overflow: hidden
- Css grid and flexbox can be used
Here is my solution of this problem: https://jsbin.com/gabumax
And here code from example:
.container {
overflow: hidden;
}
.wrapper {
margin: -10px;
display: flex;
flex-wrap: wrap;
}
.item {
flex: 0 0 auto;
padding: 10px;
background-color: red;
margin: 10px;
}
<div class="container">
<div class="wrapper">
<div class="item">Width of items can vary</div>
<div class="item">This example works</div>
<div class="item">But there is a problem</div>
<div class="item">Dye to overlow:hidden</div>
<div class="item">It is impossible to place here</div>
<div class="item">Overflowing content</div>
<div class="item">Such as dropdowns</div>
</div>
</div>
It works, but the only negative point here is overlow: hidden
. Because of this I can't place here dropdowns and other overflowing content.
Any better solution? Thanks in advance.