chefcurry7 chefcurry7 - 1 month ago 7
CSS Question

Keep flex items in place after deleting one item

I have the following html:

<div class="grommetux-box grommetux-box--direction-row grommetux-box--align-center grommetux-box--responsive grommetux-box--pad-none grommetux-box--wrap second-header">
<div class="grommetux-box grommetux-box--direction-row grommetux-box--responsive grommetux-box--pad-none school-info">
<header class="grommetux-box grommetux-box--direction-row grommetux-box--align-center grommetux-box--pad-horizontal-none grommetux-box--pad-vertical-none grommetux-box--pad-between-small grommetux-header school-name">
<!-- react-text: 74 --><!-- /react-text -->
</header>
<header class="grommetux-box grommetux-box--direction-row grommetux-box--align-center grommetux-box--pad-horizontal-none grommetux-box--pad-vertical-none grommetux-box--pad-between-small grommetux-header grommetux-header--small school-code">
<!-- react-text: 76 -->School Code: <!-- /react-text -->
</header>
</div>
<div class="grommetux-box grommetux-box--direction-row grommetux-box--responsive grommetux-box--pad-none search-box">

</div>
</div>


My CSS

.grommetux-box {
display: -ms-flexbox;
display: flex;
background-position: 50%;
background-size: cover;
background-repeat: no-repeat;

}

.grommetux-box--direction-row {
-ms-flex-direction: row;
flex-direction: row;
}

.search-box {
text-decoration: none;
justify-content: flex-end;
}

.school-info {
text-indent: inherit;
flex-direction: inherit;
justify-content: flex-start;
display: flex;
}


Sorry this code doesn't show the whole picture but basically my issue is when I delete the first inner div, the second inner div replaces it by taking its place (moving left). How can I design my flex so that if I delete one, it doesn't effect the position of the other?

Answer

In case, there are multiple items inside a flex-container and we remove one or more items, browser will recalculate and update the position of rest of the items automatically.

There is one possibility though i.e instead of removing items from the DOM we just hide them from the view with visibility: hidden. This css property hides the elements from view but keep them in DOM. As a result elements with such style will be hidden but keep the space in view.

A quick demo is in below snippet:

.container {
  min-height: 200px;
  display: flex;
}

.item {
  background: blue;
  margin: 10px;
  width: 15%;
}

.item.hidden {
  visibility: hidden;
}
<div class="container">
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item hidden"></div>
  <div class="item"></div>
</div>

Comments