shou2017.com
JP

How to Truncate Overflowing Text in Bootstrap 3

Tue May 22, 2018
Sat Aug 10, 2024

Since Bootstrap is responsive, if the text in a select box is too long, the select box itself becomes longer.

Here’s a note on how to truncate overflowing text.

The example uses Rails with Haml.

In the following case, the text 1111111111111111 in --未選択1111111111111111-- overflows. We’ll truncate it.

= f.collection_select(:product_id, Product.all, :id, :name,
{:include_blank => "--未選択11111111111111111111111111111111111111111111111111111111111111111111--", :selected => @select_option_product_val} ,
{:class => "form-control category_select_box"})

While you could use JavaScript to handle this, we’ll achieve it simply with CSS.

We’ll use the CSS property text-overflow.

For more details, refer to text-overflow.

In this case, we’ll customize Bootstrap by adding text-overflow to form-control. However, directly overwriting Bootstrap is not ideal, so we’ll add multiple classes to override it.

The CSS looks like this:

.form-control--extend {
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
  width: 100px !important;
}

Finally, add this to the Haml:

= f.collection_select(:product_id, Product.all, :id, :name,
   {:include_blank => "--未選択11111111111111111111111111111111111111111111111111111111111111111111--", :selected => @select_option_product_val} ,
   {:class => "form-control form-control--extend  category_select_box"})
See Also