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

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

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



2条回答
  •  清酒与你
    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;
    }

提交回复
热议问题