Search code examples
cssflexboxtailwind-csscss-grid

Place one item in center, one at the end


I have a css grid with 3 columns. Each column contains a title and a checkbox. I would like to have the title at the 'true' center of the column, the checkbox at the end of the column. However, the width of the columns might change so I can't statically add a margin to the checkbox.

I have this:

enter image description here

I want this:

enter image description here

I tried to set the checkbox position: absolute so the text can easily be centered, since the width of the checkbox is ignored. However this would require me to get the width of the column with javascript and programmatically set the margin of the checkbox so it always appears at the end.

Is there a better/css-only way to achieve this?

Minimal example:

<div className="grid grid-cols-3">
  <div>
    <span>Plannable</span>
    <input type="checkbox" />
  </div>

  <div>
    <span>Archive</span>
    <input type="checkbox" />
  </div>

  <div>
    <span>Export</span>
    <input type="checkbox" />
  </div>
</div>


Solution

  • The whole scenario isn't very clear because you shared a very basic html not strictly matching the picture shown. Plus there's no reference to what are the styles engaged (probably tailwind).

    To center the span you can set its container as display: flex and setting its position: relative will allow you to have its checkbox absolute positioned to its far right.

    This is an example:

    .grid{
      display: grid;
    }
    
    .grid-cols-3{
      grid-template-columns: 1fr 1fr 1fr;  
    }
    
    .grid > div {
      border: solid 1px;
      background: lightgray;
      
      /*centering content both horizontally and vertically*/
      position: relative;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    
    /*position the checkbox at the far right of its container*/
    .grid > div input {
      position: absolute;
      right: 0;
    }
    <div class="grid grid-cols-3">
       <div>
          <span>Plannable</span>
          <input type="checkbox"/>
       </div>
    
       <div>
          <span>Archive</span>
          <input type="checkbox"/>
       </div>
    
       <div>
          <span>Export</span>
          <input type="checkbox"/>
       </div>
    </div>