Search code examples
csscss-grid

CSS Grid: Start column at specific x position


I am trying to achieve a CSS grid layout with three columns: Column A and B are always equal to a certain width to let column C start at the same location unless the content in A and/or B becomes too wide.

Or to describe it another way: If A gets bigger, the needed extra width is taken out of B instead of moving both B and C further to the right.

Alternatively, can A and B be placed in the same column but be displayed inline?

I know that this could be achieved by wrapping A and B in another container element, but could it be done using just CSS grid?

|<--A-->|<---B--->|<-------C------->|

where:
A + B + C = 100%
A + B = min(30em)
A = min(18em)

Solution

  • You can do this considering an extra hidden element that you place on both A and B column and you define a min-width on it. It's a bit tricky but the idea is that the width of both column will obey to the contraint of A and B and the hidden element.

    Here is an example to illustrate the trick. I replaced 30em by 200px and 18em by 50px

    .container {
      display: grid;
      grid-template-columns: auto auto 1fr;
      grid-template-rows:1fr 0;
      height: 30px;
      color:#fff;
      margin:5px;
    }
    
    .A {
      background: red;
      min-width:50px;
    }
    
    .B {
      background:blue;
    }
    
    .C {
      background:green;
    }
    .container::after {
      content: "";
      grid-column: span 2;
      min-width: 200px;
    }
    <div class="container">
      <div class="A"></div>
      <div class="B"></div>
      <div class="C">text here</div>
    </div>
    
    <div class="container">
      <div class="A">some text</div>
      <div class="B"></div>
      <div class="C">text here</div>
    </div>
    
    <div class="container">
      <div class="A"></div>
      <div class="B">some text</div>
      <div class="C">text here</div>
    </div>
    
    <div class="container">
      <div class="A">some text</div>
      <div class="B">some text</div>
      <div class="C">text here</div>
    </div>
    
    <div class="container">
      <div class="A"></div>
      <div class="B">more and more and more text here</div>
      <div class="C">text here</div>
    </div>
    
    <div class="container">
      <div class="A">more and more  text here</div>
      <div class="B">more and more  text here</div>
      <div class="C">text here</div>
    </div>

    The only drawback or probably a simple observation is that the width of A and B will depend on the content of both and the min-width applied on A will make it grow more in case both are empty.