Foo
Bar
...">

Scrolling flexible container does not match centered elements

HTML:

<div id="container"> <div class="item">Foo</div> <div class="item">Bar</div> </div> 

CSS

 #container { display: flex; justify-content: center; overflow: auto; } .item { flex-grow: 1; min-width: 200px; max-width: 300px; } 

When the above container shrinks to less than 400 pixels, a horizontal scrollbar appears as expected. However, the first element is partially covered by the left edge of the container, even if it scrolls all the way to the left. When the container is compressed, more of the item closes.

Demo: http://jsfiddle.net/FTKcQ/ . Change the frame size for observation. Tested on Chrome 30 and Firefox 24.

If justify-content changed from center to any other value (for example, space-between ), then all content is displayed by scrolling. Why do centered objects behave differently?

The goal is to have a series of centered elements, each of which will grow in width between a certain range. If the container cannot match all the elements of the minimum width, it must scroll to display them all.

+7
flexbox css3
source share
2 answers

According to MDN (Flex Element Considerations) , this behavior is expected:

Flexbox alignment properties perform true centering, unlike other centering methods in CSS. This means that the flex elements will remain centered even if they overfill the flex container. Sometimes this can be problematic if they overflow the top edge of the page or the left edge, since you cannot scroll this area even if there is content! In a future version, alignment properties will be expanded to have a “safe” option.

For now, if this is troubling, you can instead use the fields to center, as they will respond in a “safe” way and stop centering if they overflow. Instead of using alignment properties, simply place the automatic fields on the flex items that you want to center. Instead of defensible properties, place automatic fields on the outer edges of the first and last flex items in the floppy disk container.

So, you can achieve the expected result using the fields for alignment. Just add margin-left: auto for the first element and margin-right:auto for the last.

My demo: http://jsfiddle.net/WFxQk/

+15
source share

try with style sheet

  #container {
         background-color: green;
         display: flex;
         / * justify-content: center * /;
         align-items: center;
         overflow: auto;
     }
     .item {
         background-color: white;
         border: 1px solid black;
         flex-grow: 1;
         flex-shrink: 1;
         flex-basis: auto;
         min-width: 200px;
         max-width: 300px;
         margin: auto;
     }
    
I removed justify-content , setting it to flex-start by default. And added margin:auto , which seems to align the center.

Updated demo: http://jsfiddle.net/FTKcQ/1/

+1
source share

All Articles