skip to Main Content

I have a bootstrap-vue table that looks like this;

enter image description here

Here is the code;

<template>
  <div>
    <b-table hover :items="items"></b-table>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        items: [
          { age: 40, first_name: 'Dickerson', last_name: 'Macdonald' },
          { age: 21, first_name: 'Larsen', last_name: 'Shaw' },
          {
            age: 89,
            first_name: 'Geneva',
            last_name: 'Wilson',
            _rowVariant: 'danger'
          },
          {
            age: 40,
            first_name: 'Thor',
            last_name: 'MacDonald',
            _cellVariants: { age: 'info', first_name: 'warning' }
          },
          { age: 29, first_name: 'Dick', last_name: 'Dunlap' }
        ]
      }
    }
  }
</script>

Suppose the table has many rows. I would like to pin the top header row such that when I scroll down the table, the header row showing the column names remains at the top. This makes the table more readable.

The table code was provided in bootstrap-vue documentation.

https://bootstrap-vue.org/docs/components/table

I am using Vue v2.6 and BootstrapVue.

2

Answers


  1. You will need to style the element in question with

    position: sticky;
    

    See: https://developer.mozilla.org/en-US/docs/Web/CSS/position

    Where you also have a demo:

    .sticky {
      position: -webkit-sticky;
      position: sticky;
      top: 0;
      background-color: yellow;
      padding: 50px;
      font-size: 20px;
    }
    <div class="sticky">foo</div>
    <div style="height: 2000px;"></div>

    You will therefore need to look into what the structure is that Vue generates for you and make sure you make the style of position: sticky; to the element whose position needs to be sticky.

    Login or Signup to reply.
  2. BootstrapVue’s table provide sticky-header prop for this purpose.

    As outlined in their documentation, using

    <b-table :sticky-header="true">
      ...table contents here
    </b-table>
    
    • sets the height of the table to 300px
    • sets table’s overflow to auto
    • sets table’s position to relative
    • sets the table header’s position to sticky

    Important: all of the above are required for the table header to be sticky relative to the table, not to the page. If you use @LajosArpad’s solution, the table will be sticky in relation to the page, so when scrolling past the table the table header will still remain sticky, which is probably not the desired result.

    If you want the table to have any other height than 300px, you have to pass it as the value of sticky-header prop:

    <b-table sticky-header="80vh">
      ...table contents here
    </b-table>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search