Bootstrap 4 - how to make 100% width search input

2019-01-17 11:35发布

问题:

How to make 100% width of the search input in navbar?

The field is limited in width:

<nav class="navbar navbar-light navbar-dark bg-inverse">
  <a class="navbar-brand" href="#">Navbar</a>
  <ul class="nav navbar-nav">
    <li class="nav-item active">
      <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
    </li>
    <li class="nav-item">
      <a class="nav-link" href="#">Features</a>
    </li>
    <li class="nav-item">
      <a class="nav-link" href="#">Pricing</a>
    </li>
    <li class="nav-item">
      <a class="nav-link" href="#">About</a>
    </li>
  </ul>

  <ul class="nav navbar-nav pull-xs-right">
    <li class="nav-item">
      <form class="form-inline ">
        <input class="form-control" type="text" placeholder="Search">
        <button class="btn btn-outline-success" type="submit">Search</button>
      </form>
    </li>
    <li class="nav-item">
      <a class="nav-link" href="#">User Name</a>
    </li>
  </ul>
</nav>

Here is the fiddle:

https://jsfiddle.net/Dieselnick/tdoz2o4d/

回答1:

UPDATED 2018

As of Bootstrap 4 the Navbar is flexbox so creating a full-width search input is easier. You can simply use w-100 and d-inline utility classes:

<form class="mx-2 my-auto d-inline w-100">
   <div class="input-group">
      <input type="text" class="form-control" placeholder="...">
       <span class="input-group-append">
       <button class="btn btn-outline-secondary" type="button">GO</button>
       </span>
    </div>
</form>

http://www.codeply.com/go/sbfCXYgqoO


Bootstrap 3 (original answer)

You can use the text-truncate hack on the last navbar li like this..

<li class="text-truncate">
        <form class="input-group">
            <input class="form-control" name="search" placeholder="Search Here" autocomplete="off" autofocus="autofocus" type="text">
            <div class="input-group-btn">
                <button class="btn btn-outline-success" type="submit">Search</button>
            </div>
        </form>
</li>    

In Bootstrap 4, text-truncate will set:

   overflow: hidden;
   white-space: nowrap;

This enables the search form to fill the remaining width and not wrap.

Demo http://www.codeply.com/go/22naSu3c0E

Another option is to use table-cell:

<form>
        <div class="table-cell"> &nbsp; </div>
        <div class="table-cell fill-width">
            <input class="form-control" name="search" placeholder="Search Here" autocomplete="off" autofocus="autofocus" type="text">
        </div>
        <div class="table-cell">
            <button class="btn btn-outline-success" type="submit">Search</button> 
        </div>
</form>

http://www.codeply.com/go/JdbPvotSXg