'how can i change the gap of only element
i am creating something with css flexbox and use gap to give spacing between elements but now i want to change the spacing of only one element like
.container{
display: flex;
gap: 20px;
}
.items{
width: 100px;
height: 100px;
background: red;
}
.item-4{
background: blue;
}
<div class="container">
<div class="items item-1"></div>
<div class="items item-2"></div>
<div class="items item-3"></div>
<div class="items item-4"></div>
<div class="items item-5"></div>
<div class="items item-6"></div>
</div>
Now I want to change the gap of blue box to 5px from 20px is there any way to do this
Solution 1:[1]
The
gapproperty only applies to flex-parents, not flex-items.To adjust the spacing of flex-items use an overridden
marginproperty instead.For
flex-direction: horizontalyou'll want to setmargin-leftandmargin-right(ormargin-inline-startandmargin-inline-end).For
flex-direction: verticalyou'll want to setmargin-topandmargin-bottom(ormargin-block-startandmargin-block-end).To have a larger effective gap then set any positive margin value.
- e.g. with
gap: 5pxandmargin-left: 1pxthen the effective gap to the left will be6px.
- e.g. with
To have a smaller effective gap then set a negative margin value.
- e.g. with
gap: 5pxandmargin-left: -1pxthen the effective gap to the left will be4px.
- e.g. with
This approach won't work for items with
margin: auto, but that's okay becausegap:isn't useful withautomargins anyway.
In your case, there's 20px on either side of your items, so applying a margin-left of -15px will give you a 5px left gap, and a margin-right of -15px will give you a 5px right gap.
Which looks like this:
Like so:
.container{
display: flex;
gap: 20px;
}
.items{
width: 100px;
height: 100px;
background: red;
}
.item-4 {
background: blue;
margin-left: -15px; /* Adapt 20px gap to 5px */
margin-right: -15px; /* Adapt 20px gap to 5px */
}
<div class="container">
<div class="items item-1"></div>
<div class="items item-2"></div>
<div class="items item-3"></div>
<div class="items item-4"></div>
<div class="items item-5"></div>
<div class="items item-6"></div>
</div>
Solution 2:[2]
.container{
display: flex;
gap: 20px;
}
.items{
width: 100px;
height: 100px;
background: red;
}
.item-4{
background: blue;
margin-left: -15px;
}
<div class="container">
<div class="items item-1"></div>
<div class="items item-2"></div>
<div class="items item-3"></div>
<div class="items item-4"></div>
<div class="items item-5"></div>
<div class="items item-6"></div>
</div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Manoj Tolagekar |

