How can I let a div fill 100% width if no other elements are beside it?

后端 未结 3 1638
小鲜肉
小鲜肉 2021-02-18 13:00

I have simple markup like this (a tab menu):

相关标签:
3条回答
  • 2021-02-18 13:38

    You mean like flexbox?

    .container {
      display: flex;
      height: 50px;
      margin-bottom: 1em;
    }
    [class*="tab"] {
      flex: 1;
      border: 1px solid red;
    }
    <div class="container">
      <div class="tab1"></div>
    </div>
    
    <div class="container">
      <div class="tab1"></div>
      <div class="tab2"></div>
    </div>
    
    <div class="container">
      <div class="tab1"></div>
      <div class="tab2"></div>
      <div class="tab3"></div>
    </div>

    Or CSS Tables

    .container {
      display: table;
      height: 50px;
      width: 100%;
    }
    [class*="tab"] {
      display: table-cell;
      border: 1px solid red;
    }
    <div class="container">
      <div class="tab1"></div>
    </div>
    
    <div class="container">
      <div class="tab1"></div>
      <div class="tab2"></div>
    </div>
    
    <div class="container">
      <div class="tab1"></div>
      <div class="tab2"></div>
      <div class="tab3"></div>
    </div>

    0 讨论(0)
  • 2021-02-18 13:41

    Depending on what browsers you need to support, you may be able to use flexbox:

    $('.tab').click(function() {
      $(this).css('display', 'none');
    });
    .container {
      display: flex;
    }
    
    .tab {
      border: 1px solid black;
      padding: 5px;
      flex: 1;
      margin: 5px;
    }
    <p>Click a tab to remove it</p>
    <div class="container">
       <div class="tab">Tab 1</div>
       <div class="tab">Tab 2</div>
       <div class="tab">Tab 3</div>
    </div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

    0 讨论(0)
  • 2021-02-18 14:00

    You can use display:table and display:table-cell see below code

    HTML:

    <div class="container">
       <div class="tab">Tab 1</div>
       <div class="tab">Tab 2</div>
       <div class="tab">Tab 3</div>
    </div>
    

    CSS:

    .container {
      display: table;
      width:100%;
    }
    
    .tab {
      border: 1px solid black;
      padding: 5px;
      display: table-cell;
      margin: 5px;
    }
    
    0 讨论(0)
提交回复
热议问题