Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a specific flexbox gap in CSS

I'm trying to achieve a flexbox layout with just one flex-grow element and a variable number of smaller elements around it. I need a gap between the elements that's a fixed width - exactly one pixel. Here's a diagram of what I want:

The blue element grows to fill the space, but has a 1px gap in between every element.

How do I create this fixed width gap?


Potential non-flexbox solution

I didn't know how to achieve that precise 1 pixel gap in flexbox, so I was trying to create it in a grid layout. I ran into a different issue of not having a flex-grow property for grid children:

.box {
  display: grid;
  grid-auto-flow: column;
  grid-gap: 1px;
}
.big-element {
  // <- Need something similar to flex-grow for this element
}
like image 303
Jae Kwak Avatar asked Feb 03 '18 19:02

Jae Kwak


2 Answers

The CSS spec has recently been updated to apply gap properties to flexbox elements in addition to CSS grid elements. This feature is supported on the latest versions of all major browsers. With the gap property, you can get what you want just by adding a column-gap: 1px rule.

like image 128
neurodynamic Avatar answered Oct 14 '22 02:10

neurodynamic


You may use margin/padding to create this gap:

.container {
  border: 1px solid;
  display: flex;
  height: 20px;
  margin:10px 0;
  padding: 1px 0 1px 1px;
}

.e {
  flex: 1;
  margin-right: 1px;
  background: red;
}

.b {
  width: 200px;
  margin-right: 1px;
  background: green;
}
<div class="container">
  <div class="e"></div>
  <div class="e"></div>
  <div class="b"></div>
</div>
<div class="container">
  <div class="e"></div>
  <div class="e"></div>
  <div class="b"></div>
  <div class="e"></div>
  <div class="b"></div>
</div>
<div class="container">
  <div class="e"></div>
  <div class="e"></div>
  <div class="e"></div>
  <div class="b"></div>
  <div class="e"></div>
  <div class="e"></div>
  <div class="e"></div>
  <div class="e"></div>
</div>
like image 41
Temani Afif Avatar answered Oct 14 '22 02:10

Temani Afif