I want to render a single row of divs with an equal 1px gap between them, but this is proving harder than I thought.
I'm trying to accomplish this with either css-grid or flexbox.
with CSS-grid I tried the following:
const Container = styled.div`
width: 100%;
height: 20px;
display: grid;
grid-auto-flow: column;
column-gap: 1px;
`
Which resulted in this:
(all of the divs inside should be equal size and have a 1px gap inbetween them).
However as you can tell, there is a gap missing between several of the divs...
If I increase the gap size to 2px it becomes apparent that it's a space issue.
Now you can see that some columns have a gap of 2px and some have a gap of 1px (likely because there isn't "room" for all of them to have exactly 1 or 2px gap inbetween and still keep the divs an equal size.
And as expected if I resize the overall container these are in, the amount and location of the missing gaps change. This confirms it's a problem with the available space.
However what I want to happen in this case is to have priority on the gaps rather than the divs being the same size. I would prefer if one (or multiple if requires) of the divs inside are 1px less wide than a missing gap as that would be much less noticeable.
Resizing the main container to match a scenario where it fits perfectly is not an option as it's a responsive design.
I also tried to use flexbox gap instead but it results in the same CSS issue with inconsistent gaps:
const Grid = styled.div`
width: 100%;
height: 20px;
display: flex;
gap: 1px;
`
const Item = styled.div`
height: 100%;
display: flex;
flex: 1;
`
How do I force the gaps to always be the same size, but compromise on the size of the divs to make sure the gaps are always exactly 1px wide?
CodePudding user response:
Try this css:
const note = document.querySelector('.main');
note.style.display = 'flex';
note.style.gap = '1px';
note.style.flexWrap = 'wrap';
.main>div {
flex: 1 0 25px;
background-color: green;
/*25 px is minimum width of content check flex-basis*/
}
<div >
<div>a</div>
<div>a</div>
<div>a</div>
<div>a</div>
<div>a</div>
<div>a</div>
<div>a</div>
<div>a</div>
<div>a</div>
<div>a</div>
<div>a</div>
<div>a</div>
<div>a</div>
</div>
CodePudding user response:
I had a similar problem with gaps and width.
First, it's important to understand the problem. When you set width to 100%, you are telling the div to take up a certain amount of space, in this case 100%.
A better approach would be to give the div/element a height you want, but set the width to auto, which is more dynamic and won't encroach on the gaps you're trying to set.
.my-div {
height: 100px;
width: auto;
display: 'flex';
gap: 2px;
}