If you want to ensure that "Image 1 of 2" (center column) stays in the middle of the screen, here's what you can do:
- Set the left and right columns with
flex: 1 1 50%
- For the center column, use
flex: 0 0 auto
By defining the left and right columns with a base of 50%, they will have equal weight regardless of content width differences. The center column will then adjust its size based on the available space between the left and right columns to keep everything centered.
If you want the center column to start wrapping at a specific width, add a max-width
and text-align: center
to it.
That's pretty much all there is to it!
<div className={css.title}>
<div className={css.row}>
<div className={css.columnLeft}>
<div className={css.header}>Images</div>
</div>
<div className={css.columnCenter}>
<strong>Image 1 of 2</strong>
</div>
<div className={css.columnRight}>
<Icon />
</div>
</div>
</div>
CSS:
.row {
display: flex;
}
.columnLeft,
.columnRight {
flex: 1 1 50%;
}
.columnCenter {
flex: 0 0 auto;
display: flex;
justify-content: center;
}
.columnRight {
display: flex;
flex-direction: row-reverse;
}
Try out the HTML demo below:
.row {
display: flex;
justify-content: center;
}
.columnLeft, .columnRight {
flex: 0 1 50%;
border: 1px solid red;
}
.columnCenter {
flex: 0 0 auto;
display: flex;
justify-content: center;
}
.columnRight {
display: flex;
flex-direction: row-reverse;
}
.middle {
width: 1px;
height: 2rem;
background-color: red;
}
<div class="row">
<div class="columnLeft">
<div class="header">More content on left side</div>
</div>
<div class="columnCenter">
<strong>I am centered</strong>
</div>
<div class="columnRight">Icon</div>
</div>
<div class="row">
<div class="middle" />
</div>
Additional Notes:
1 - I modified the class name of the central flexible element from 'columnRight' to 'columnCenter' for clarity. I also wrapped the <Icon />
in a .columnRight
container since having the center element labeled as 'columnRight' seemed confusing.
2 - Remember that flex layouts adapt to different content sizes, so if one column has significantly more content than the others, the centering may not be perfect. To maintain center alignment no matter what, consider setting a max-width on the side columns.