How to keep the middle item centered when side items have different widths with CSS?

Spread the love

Sometimes, we want to keep the middle item centered when side items have different widths with CSS.

In this article, we’ll look at how to keep the middle item centered when side items have different widths with CSS.

How to keep the middle item centered when side items have different widths with CSS?

To keep the middle item centered when side items have different widths with CSS, we use the flex-basis property.

For instance, we write

.parent {
  display: flex;
  justify-content: space-between;
}

.left,
.right {
  flex-grow: 1;
  flex-basis: 0;
}

to make the container element a flex container with display: flex;.

We make the child elements spread inside the container with justify-content: space-between;.

Then we flex-basis: 0; to the left and right elements to stop them from changing the position of the middle element.

Conclusion

To keep the middle item centered when side items have different widths with CSS, we use the flex-basis property.

Leave a Reply

Your email address will not be published. Required fields are marked *