CSS

Efficiently Control Flex Item Sizing and Spacing

Learn to precisely control the growth, shrink, and initial size of flex items using the `flex` shorthand property, combined with `gap` for perfect spacing.

.flex-container {
  display: flex;
  flex-wrap: wrap; /* Allows items to wrap to the next line */
  gap: 20px;       /* Spacing between flex items (both row and column) */
  padding: 20px;
}

.flex-item {
  /* flex: <flex-grow> <flex-shrink> <flex-basis> */
  /* This item will grow if space is available (1), shrink if needed (1),
     and its initial size will be 200px. */
  flex: 1 1 200px;
  background-color: #cfe2ff;
  border: 1px solid #007bff;
  padding: 15px;
  text-align: center;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  min-width: 0; /* Prevents overflow issues with flex-basis */
}

/* Example of a fixed-size item that doesn't grow or shrink */
.flex-item.fixed {
  flex: 0 0 150px; /* Will not grow (0), will not shrink (0), basis 150px */
  background-color: #d1e7dd;
  border-color: #198754;
}
How it works: This snippet demonstrates how to finely control the behavior of flex items using the `flex` shorthand property and manage their spacing with `gap`. The `flex` property combines `flex-grow` (how much an item will grow relative to others), `flex-shrink` (how much it will shrink relative to others), and `flex-basis` (its ideal initial size before growing or shrinking). The `gap` property provides a modern and efficient way to add space between flex items, removing the need for negative margins or complex calculations, and `flex-wrap: wrap` ensures items flow onto new lines as needed.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs