Warm tip: This article is reproduced from serverfault.com, please click

Prevent linebreaks in labels in Boostrap?

发布于 2020-11-30 07:54:59

I have developed a form using Bootstrap and I need the form to behave correctly on different devices. In one part of my form I have three inputs on one row, which usually works fine. But when I emulate different devices in the browser I see that the labels are broken into two lines when the screen width is to narrow. This makes sense of course, but I need a solution to prevent this. Is it possible? I can accept that the label/icon is cropped, but not divided to several lines. The form is generated by PHP and the labels may vary in length.

My expected result is like this (labels will have an icon on their side):

enter image description here

But when the screen width gets too narrow it looks like this:

enter image description here

I don't want the icon to appear on a new line. I would rather prefer that it was hidden if there's no space for it.

In the sample code below I have forced the width to 350px to illustrate the problem. When using width 400px or more it looks good:

<html>

<head>
  <title>Example</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
  <script src='https://kit.fontawesome.com/a076d05399.js'></script>
</head>

<body>
  <div class="container" style="max-width:350px">
    <form>
      <div class="form-row">
        <div class="col-4">
          <div class="form-group">
            <label for="input-1">First label <span class='fas fa-info-circle'></span>
                </label>
            <input id="input-1" class="form-control" name="input1" type="text">
          </div>
        </div>
        <div class="col-4">
          <div class="form-group">
            <label for="input-1">Second label <span class='fas fa-info-circle'></span></label>
            <input id="input-1" class="form-control" name="input2" type="text">
          </div>
        </div>
        <div class="col-4">
          <div class="form-group">
            <label for="input-1">Third label  <span class='fas fa-info-circle'></span></label>
            <input id="input-1" class="form-control" name="input3" type="text">
          </div>
        </div>
      </div>
    </form>
  </div>
</body>

</html>
Questioner
Gowire
Viewed
0
Swaraj Gandhi 2020-11-30 16:09:59

First of all you have to find at which device width, it is breaking, after that you can add media query in css to hide the icon.

Like this:

@media screen and (max-width: 350px) {
  .fa-info-circle {
    display: none;
  }
}

this will hide the icon for width 350px or less.