Using CSS, how to create a two-column grid with equal-width columns that are “only as narrow as required”?

前端 未结 2 1280
后悔当初
后悔当初 2021-01-20 03:18

Assuming I have a piece of HTML that is structured like this:



相关标签:
2条回答
  • 2021-01-20 03:51

    Just revisited this now since CSS Grid has become much more supported. One solution for CSS Grid would be this:

    .linkgrid {
      display: inline-grid;
      grid-template-columns: repeat(2, 1fr);
      column-gap: 10px;
      row-gap: 10px;
    }
    
    .gridentry > * {
      display: block;
    
      padding: 10px;
    
      text-align: center;
      
      background-color: red;
      color: white;
    
      /* This is helpful if the texts get too long to break them "naturally": */
      /* word-break: break-all; */
    }
    <div class="linkgrid">
      <div class="gridentry">
        <a href="#">Loooooooooooooong</a>
      </div>
      <div class="gridentry">
        <a href="#">Short</a>
      </div>
      <div class="gridentry">
        <a href="#">Meeeedium</a>
      </div>
      <div class="gridentry">
        <a href="#">Short</a>
      </div>
      <div class="gridentry">
        <a href="#">Short</a>
      </div>
    </div>

    0 讨论(0)
  • 2021-01-20 04:02

    After fiddling around with this for quite a while and getting a very helpful answer to another question that was related to this one, I managed to finally find a solution:

    .linkgrid {
      max-width: 50%;
      display: table;
    }
    
    .gridentry:nth-child(odd) {
      float: left;
      width: 100%;
    }
    
    .gridentry:nth-child(even) {
      width: 100%;
      margin-left: 100%;
      margin-right: -100%;
    }
    
    .gridentry:nth-child(even):after {
      content: '';
      display: block;
      clear: left;
    }
    
    .gridentry > * {
      display: block;
      
      margin-bottom: 10px;
      padding: 10px;
    
      background-color: red;
      text-align: center;
    
      /* This is helpful if the texts get too long to break them "naturally": */
      /* word-break: break-all; */
    }
    
    .gridentry:nth-child(odd) > * {
      margin-right: 5px;
    }
    
    .gridentry:nth-child(even) > * {
      margin-left: 5px;
    }
    
    .gridentry a {
      color: white;
    }
    <div class="linkgrid">
      <div class="gridentry">
        <a href="#">Loooooooooooooong</a>
      </div>
      <div class="gridentry">
        <a href="#">Short</a>
      </div>
      <div class="gridentry">
        <a href="#">Meeeedium</a>
      </div>
      <div class="gridentry">
        <a href="#">Short</a>
      </div>
      <div class="gridentry">
        <a href="#">Short</a>
      </div>
    </div>

    0 讨论(0)
提交回复
热议问题