skip to Main Content

I have a structure like this one with one div containing two others:

<div class="list-detail">
    <div class='first-list'>
 
    </div>
    <div class='second-list'>
 
    </div>
</div>

I am populating them using jquery and their css looks like this:

.list-detail{
    display:flex;
}
.event-list, .match-list{
    width:100%;
    margin-left: 1%;
}

The width:100% allows the divs to span the entire screen with width 50% of the screen each.
The div second-list can be empty, and if so I hide it. The problem comes when it is hidden, the div first-list takes the entirety of the screen, and in this situtation I would like the div to be centered and taking 50% of the screen. How can I achieve this?

I already tried removing/modifying the width:100%, since it is probably the reason why it spans the entire screen when the div second-list is hidden but then it messes up the use case where both divs are full with elements. They are very small / not centered at all.

2

Answers


  1. If I understand correctly you want to center the div.first-list when the div.second-list is empty, and you also want the div.first-list to be at 50% of the space,
    here is the solution

        
        let second = $('.second-list').text();
        if(second.length == 0){
          $('.second-list').remove();
        }
        
    
      
      
    .list-detail{
        display:flex;
    }
    .first-list, .second-list{
      margin: auto;
      width: 50%;
      border: 3px solid green;
      padding: 10px;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="list-detail">
        <div class='first-list'>
     Magna adipisicing consequat reprehenderit culpa. Tempor aliquip enim occaecat nisi officia amet ex quis. Culpa esse consectetur eiusmod excepteur commodo sint velit cupidatat enim consequat enim officia mollit exercitation.
        </div>
      <div class='second-list'></div>
    </div>
    Login or Signup to reply.
  2. You could set visibility to hidden but keep in mind it will hide it from UI but this div will still take up space, you could see this in example below

    Alternatively, you could set flex basis to 50% on list element and set display to none on the ones you want to hide or remove them from DOM

    Depending on what you want to achieve you could also checkout how to do it with grid

    .list-detail {
      display: flex;
      gap: 10px;
    }
    
    .first-list,
    .second-list {
      flex: 1;
      height: 100px;
      border: 4px solid blue;
    }
    
    .first-list {
      visibility: hidden;
    }
    <div class="list-detail">
      <div class='first-list'>
    
      </div>
      <div class='second-list'>
    
      </div>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search