Look at following fiddle https://jsfiddle.net/27x7rvx6
The CSS (#test
is flexbox container, and .items
are its children):
#test {
display: flex;
flex-flow: row nowrap;
justify-content: center;
width: 300px;
margin-left: 150px;
border: 2px solid red;
}
.item {
flex: 0 0 70px;
margin-right: 10px;
background: blue;
height: 70px;
border: 2px solid black;
}
There is a one line (nowrap
) flexbox with fixed size items. The container has justify-content
set to center
. Because the items can't shrink and are together wider than the container they start to overflow.
My problem is that the content overflows both to the left and to the right. Is there a way to make the content justified to center but once it starts to overflow make it act like the justify-content
property is set to flex-start
, resp. make it overflow only to right of the container?
justify-content
is not the right approach to center because of the problem you describe.
Instead, I recommend auto
margins. You can use them to center:
Prior to alignment via
justify-content
andalign-self
, any positive free space is distributed to auto margins in that dimension.
And they behave as you want with overflow:
Overflowing boxes ignore their auto margins and overflow in the end direction.
For example, you can set margin-left: auto
to the first flex item and margin-right: auto
to the last one, or insert ::before
and ::after
pseudo-elements.
.test {
display: flex;
flex-flow: row nowrap;
width: 200px;
border: 2px solid red;
margin: 10px;
}
.wide.test {
width: 500px;
}
.test::before, .test::after {
content: ''; /* Insert pseudo-element */
margin: auto; /* Make it push flex items to the center */
}
.item {
flex: 0 0 50px;
margin-right: 10px;
background: blue;
height: 50px;
border: 2px solid black;
}
<div class="test">
<div class="item"></div><div class="item"></div><div class="item"></div>
<div class="item"></div><div class="item"></div><div class="item"></div>
</div>
<div class="wide test">
<div class="item"></div><div class="item"></div><div class="item"></div>
<div class="item"></div><div class="item"></div><div class="item"></div>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With