Michiel Borkent
Michiel Borkent

Reputation: 34840

How to get bootstrap 4 flex table that does not spread over 100% of the width of the page?

In the following example, I want to format the divs like a table, but I don't want to spread the text over 100% of the width of the page. I want the columns to be as close to each other so it will read as normal text. For the example below I want to display it as:

aaa   bb   ccc ddd 
aaaaa bbbb c   dd

When I try to use Bootstrap 4's .row and .col I get the table formatting I want, but then the table spreads the text over 100% of the width of the page. How can I get the above formatting?

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<div style="font-family: Consolas;">
   <div class="d-flex p-2">
      <div>aaa&nbsp;</div>
      <div>bb&nbsp;</div>
      <div>ccc&nbsp;</div>
      <div>ddd&nbsp;</div>
   </div>
   <div class="d-flex p-2">
      <div>aaaaa&nbsp;</div>
      <div>bbbb&nbsp;</div>
      <div>c&nbsp;</div>
      <div>dd&nbsp;</div>
   </div>
</div>

EDIT: I realize using a normal table without the CSS of Bootstrap might do what I want.

Upvotes: 0

Views: 503

Answers (1)

tao
tao

Reputation: 90208

If you want the behavior of a <table>, that's what you should use.
Bootstrap only styles <table>s having the class of table, to allow using <table>s for any other purpose:

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>
<table>
  <tbody>
    <tr>
      <td>aaa&nbsp;</td>
      <td>bb&nbsp;</td>
      <td>ccc&nbsp;</td>
      <td>ddd&nbsp;</td>
    </tr>
    <tr>
      <td>aaaaa&nbsp;</td>
      <td>bbbb&nbsp;</td>
      <td>c&nbsp;</td>
      <td>dd&nbsp;</td>
    </tr>
  </tbody>
</table>

To have the Bootstrap's <table> specific styling and make the table not stretch the entire width of its parent you can give the table width: auto:

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>
<table class="table" style="width: auto">
  <tbody>
    <tr>
      <td>aaa&nbsp;</td>
      <td>bb&nbsp;</td>
      <td>ccc&nbsp;</td>
      <td>ddd&nbsp;</td>
    </tr>
    <tr>
      <td>aaaaa&nbsp;</td>
      <td>bbbb&nbsp;</td>
      <td>c&nbsp;</td>
      <td>dd&nbsp;</td>
    </tr>
  </tbody>
</table>

You can also rely on Bootstrap's grid system to limit the width of the <table> or of its parent.

Upvotes: 2

Related Questions