Search code examples
twitter-bootstrapbootstrap-4grid-layout

bootstrap grid equal column width


I have a simple two column key-value grid that spans a set of rows

..
<div class="row">
  <div class="col-md-auto">KEY</div>
  <div class="col">VALUE</div>
</div>
..

I would like to have a table like behavior, that is the key column auto adapts in width to the widest key across the rows.

This would be best done with a table like:

<div class="table-responsive">
  <table class="table">
    ...
  </table>
</div>

However, I would like to have the stack ability for smaller displays that the grid system gives.

Large display

KEY, VALUE

Small display

KEY,
VALUE,

I would like to use the auto adjust since the 12 grids available don't suit me all that well.


Solution

  • Based on your description, what you want is this:

    <div class="container">
        <div class="row">
            <div class="col-12 col-md-auto">KEY</div>
            <div class="col">VALUE</div>
        </div>
    </div>

    That shrinks the key column as much as possible on medium (md) screens, but on smaller screens, the key column snaps to full width. The value column occupies whatever remaining space there is available which on smaller screens is the full width. That's why both columns snap to full width on smaller screens.

    I used the md class because that's what you have in your code. For large screens, you'd need to use the lg class.

    Also, you could put multiple key/value columns into the same row by separating them with a div that has the class of w-100 like this:

    <div class="container">
        <div class="row">
            <div class="col-12 col-md-auto">KEY</div>
            <div class="col">VALUE</div>
            <div class="w-100"></div>
            <div class="col-12 col-md-auto">KEY</div>
            <div class="col">VALUE</div>
        </div>
    </div>