Home > Mobile >  How to make autoresize flex elements?
How to make autoresize flex elements?

Time:05-02

I have some squares inline:

.parent {
  padding: 0;
  list-style: none;
  display: flex;
  gap: 20px;
}

.parent div {
  background: red;
  width: 120px;
  height: 120px;
}
<div >
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>

I need to resize .parent div if the blocks are not fitted inline.

How to do that using flex?

CodePudding user response:

If you want the divs to resize, you should not use absolute units such as px, but write them as relative size against the parent div, such as in %. However, you might want to max them out at a certain size before they get too big, so you might want to use a max-width such as follows.

.parent {
  padding: 0;
  list-style: none;
  display: flex;
  gap: 20px;
}

.parent div {
  background: red;
  width: 20%;
  max-width: 120px;
  aspect-ratio: 1;
}
<div >
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>

  • Related