22

How do I get auto width in Bootstrap 4 columns?

I need 2 column in a row without fixed width, is it possible?

1

2 Answers 2

51

Use col class. You can use col-* also eg: col-md

 <div class="row">
        <div class="col">Col1</div>
        <div class="col">Col2</div>
    </div>

If you use col class the columns will be of equal width. If you use col-auto the width of the column will be the width of the contents in the column.

You can even use a combination of both, like below. In this case the first column width will be equal to the contents of that column. Second column width take the rest of width.

    <div class="row">
        <div class="col-auto">Col1</div>
        <div class="col">Col2</div>
    </div>

Some examples

When using 2 col classes

enter image description here

<div class="container">
  <div class="row">
    <div class="col">
      col - equal columns
    </div>
    <div class="col">
       col - equal columns
    </div>    
  </div>
</div>

When using col-auto for first column and col for second.

enter image description here

<div class="container">
  <div class="row">
    <div class="col-auto">
      col-auto - hello
    </div>
    <div class="col">
       col - this column takes rest of available space
    </div>    
  </div>
</div>

Play here

/* CSS used here will be applied after bootstrap.css */

.container {
  width: 600px;
}

.row {
  padding: 10px;
}

.col,
.col-auto {
  border: 1px solid #CCC;
  padding: 5px;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container">
  <div class="row">
    <div class="col-auto">
      col-auto - hello
    </div>
    <div class="col">
      col - this column takes rest of available space
    </div>
  </div>
</div>

Sign up to request clarification or add additional context in comments.

3 Comments

Is there something similar for a whole table? I try to layout a table with bootstrap and would like the table to fit the column width to the longest cell in the column
@Qw3ry I did not get it clearly !! I suggest asking this as a new question, so that you will get more inputs.
Actually I wanted something like this and I did not realize I could put another row inside of a col... But in my defense, I'm quite new to web programming, especially when it comes to frameworks like bootstrap^^
1

Use col-auto. It will automatically take column size as per content size.

It will adjust width as per content in all devices.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.