Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

When using flex wrap, how can set another element to have a width aligned to the wrapped elements?

I’m building an application which has a container with fixed size blocks and a search box on top of the block list.

I set up block wrapping (using flex wrap) to display the blocks into multiple columns when the screen factor is large enough.

I’d like to fix the search box to the width of the blocks container. Not the full width, but the width of the actual occupied space of the blocks.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

To illustrate my goal:

enter image description here

Blue is the block container, Red is the search container and Greens are my blocks.

The Red div is 100% width of its container (div default).

I want its right side to be aligned with the right side of the last column in the flex wrap.

How can I reach my goal ?

Repro:

const listEl = document.getElementById("list");

if (!listEl) throw new Error("boom");
for (let i = 0; i < 100; i++) {
  const block = document.createElement("div");
  block.className = "block";
  block.innerText = i.toString();

  listEl.appendChild(block);
}
div {
  padding: 3px;
}

#search {
  border: solid 2px red;
}

#search input {
  width: 100%;
}

#list {
  border: solid 2px blue;
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.block {
  width: 128px;
  height: 64px;
  border: solid 2px green;
}
<div id="container">
  <div id="search">
    <input type="text" />
  </div>

  <div id="list"></div>
</div>

>Solution :

If you could change your HTML structure a little bit, with grid layout it is possible:

const listEl = document.getElementById("list");

if (!listEl) throw new Error("boom");
for (let i = 0; i < 100; i++) {
  const block = document.createElement("div");
  block.className = "block";
  block.innerText = i.toString();

  listEl.appendChild(block);
}
div {
  padding: 3px;
}

#search {
  border: solid 2px red;
  grid-column: 1/-1;
}

#search input {
  width: 100%;
}

#list {
  border: solid 2px blue;
  display: grid;
  grid-template-columns: repeat(auto-fill, 128px);
  gap: 10px;
}

.block {
  border: solid 2px green;
  height: 64px;
}
<div id="container">
  <div id="list">
    <div id="search">
      <input type="text" />
    </div>
  </div>
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading