Search code examples
responsivebootstrap-vue

b-table from BootstrapVue: responsive while fitting width to content


How can the width of a BootstrapVue b-table fit to its content while being responsive at the same time?


I've tried combining the class w-auto with the table styling responsive. As soon as I use the latter, the w-auto is overruled.
Having a responsive table is practical, because the fact of having a scrollbar when the table size exceeds the size of its container. But when that it is not the case, I would like the table being not bigger than its content.


Here is an example in codepen.io.


Solution

  • When you use the responsive prop, a wrapper <div> is added around the <table>. This means that when you use class it will be added to that wrapper <div> instead of the table itself.

    To add the class w-auto to the <table>, you should use the table-class prop instead.

    new Vue({
      el: "#app",
      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" },
            { age: 38, first_name: "Jami", last_name: "Carney" }
          ]
        };
      }
    });
    <link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap@4.5.3/dist/css/bootstrap.min.css" />
    <link href="https://unpkg.com/bootstrap-vue@2.21.2/dist/bootstrap-vue.css" rel="stylesheet" />
    
    <script src="//unpkg.com/vue@2.6.12/dist/vue.min.js"></script>
    <script src="//unpkg.com/bootstrap-vue@2.21.2/dist/bootstrap-vue.min.js"></script>
    
    
    <div id="app">
      <b-table striped hover responsive table-class="w-auto" :items="items"></b-table>
    </div>