htmlcssbootstrap-4dynamic-columns

Bootstrap 4 - Column Form Label with max width


I'm building a form in a full-width fluid layout with 2 columns, the label column and the inputs column.

the problem is because it is a fluid layout with wide screens a col-2 label is too big and col-1 is too small.

is there a way to give a max width to the col-form-label column or do i need to create some custom CSS for this columns?

simple demo : https://codepen.io/seltix/pen/aWgVjR

<div class="formcontainer">
  
  <div class="form-group row">
    <label class="col-12 col-lg-2 col-form-label">Label</label>
    <div class="col-12 col-lg-10">
      <input class="form-control" type="text" value="">
    </div>
  </div>
  
  <div class="form-group row">
    <label class="col-12 col-lg-2 col-form-label">Longer label</label>
    <div class="col-12 col-lg-10">
      <input class="form-control" type="text" value="">
    </div>
  </div>
  
  <div class="form-group row">
    <label class="col-12 col-lg-2 col-form-label">Longer label (extra)</label>
    <div class="col-12 col-lg-10">
      <input class="form-control" type="text" value="">
    </div>
  </div>
  
</div>

bootstrap 4 form source: https://v4-alpha.getbootstrap.com/components/forms/#textual-inputs


Solution

  • The max-width of col-lg-2 in bootstrap 4 is 16.6667%, and the screen size boundary is min-width: 992px. What you want to do is override the maximum width of those columns in that view using your custom class like this:

    CSS

    /* Not too wide */
        @media(min-width: 992px) {
          .col-percent-13 {
               max-width: 13% !important;
          }
        }
    
    /* A little bit narrower */
        @media(min-width: 992px) {
              .col-percent-11 {
                   max-width: 11% !important;
              }
            }
    

    Example HTML

    <!-- I want all the labels in this form to have a width of 13% -->
      <div class="form-group row">
        <label class="col-12 col-lg-2 col-form-label col-percent-13">Label</label>
        <div class="col-12 col-lg-10">
          <input class="form-control" type="text" value="">
        </div>
    

    <!-- In another form, I want all the labels to be 11% wide -->
      <div class="form-group row">
        <label class="col-12 col-lg-2 col-form-label col-percent-11">Label</label>
        <div class="col-12 col-lg-10">
          <input class="form-control" type="text" value="">
        </div>
    

    Modify the width values and class names to your preference.