Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allow flex items to keep fixed width and scroll horizontally inside container [duplicate]

Tags:

html

css

flexbox

I have a parent that's using display: flex;. It has four children (cards) currently, but it may have more. All the children need big, but equal, widths. For example, each child needs a 40% width. If that happens, only a certain amount of children will fit on the screen. I need to be able to do that, and have the rest of the children be accessible with horizontal scrolling.

explanation image

How do I achieve this? I tried using flex-wrap: no-wrap; and then increasing the width of the children, but the parent doesn't allow that. This seems intentional, but I basically want to override this behaviour.

HTML

 <div id="parent">
   <div class="children">
       <card-header>
           <b class="text"">Text</b>
       </card-header>
   </div>
 </div>

CSS

#parent {
  display: flex;
  flex-flow: row no-wrap;
  align-content: flex-start;
  justify-content: space-around;
  background-color: blue;
  height: 100%;
}

.children {
    width: 50%;
    height: 100%;
}
like image 897
naiveai Avatar asked May 23 '16 14:05

naiveai


People also ask

How do you give a fixed width to a flex item?

A flexbox item can be set to a fixed width by setting 3 CSS properties — flex-basis, flex-grow & flex-shrink. flex-basis : This property specifies the initial length of the flex item. flex-grow : This property specifies how much the flex item will grow relative to the rest of the flex items.

Which flexbox property justifies items horizontally?

We use justify-content to align the item on the main axis, which in this case is the inline axis running horizontally. You can take a look at the code of this example below. Change the size of the container or nested element and the nested element always remains centered.


1 Answers

It looks like you're searching for the CSS overflow property.

Try adding overflow-x: auto to the container.

And make the children less flexible.

Instead of this:

width: 50%;

Try this:

flex: 0 0 50%; /* don't grow, don't shrink, stay fixed at 50% width */

The initial value of flex-shrink is 1, which means the flex item will shrink to avoid overflowing the container. With the code above we override the default with 0, which essentially turns off flex shrink.

like image 79
Michael Benjamin Avatar answered Nov 28 '22 07:11

Michael Benjamin