Home > Net >  How do I set the max width of flexbox content while allowing the container to keep growing?
How do I set the max width of flexbox content while allowing the container to keep growing?

Time:09-07

Goals:

  • Dynamic number of items per row as the screen size changes
  • As screen size increases, show a max number of X items per row and keep those items centered instead of growing them with the .parent container
  • The scrollbar must remain at the max width of the .parent container.
  • The width of child items should not increase
  • Gaps between child items should not increase

Restrictions:

  • Children must be direct children of the div with the scrollbar. Cannot add a div between them. (This is because the elements are auto-generated by a 3rd party toolkit.)
  • Cannot change which element the scrollbar belongs to. It must be set on .parent.

Essentially, this is what I want on larger screens. However, I achieved this by adding a div between .parent and its children, which I can't do in the real code. enter image description here

Here is my basic structure (without the intermediate div I'm not allowed to use):

.parent {
  background-color: lightblue;
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
}

.child {
  content: "";
  width: 80px;
  height: 80px;
  margin: 10px;
  background-color: red;
}
<div >
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
</div>

CodePudding user response:

You can do this by setting a dynamic padding left and right on the parent div.

Add the following to the css rule for .parent:

  padding: 0 max(calc(50vw - 832px / 2), 20px);
  width: 100%;
  box-sizing: border-box;

Adjust the max width of the area with the red boxes by changing the 832px part to the width you would like. 832 gets you 8 boxes.

.parent {
  background-color: lightblue;
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  padding: 0 max(calc(50vw - 832px / 2), 20px);
  width: 100%;
  box-sizing: border-box;
}

.child {
  content: "";
  width: 80px;
  height: 80px;
  margin: 10px;
  background-color: red;
}
<div >
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
</div>

  • Related