0

Existing code

  • index.html:

    <!DOCTYPE html>
    <head>
      <title>Test</title>
      <link href="stylesheets/index.css" rel="stylesheet"
            type="text/css" />
    </head>
    <ul>
      <li>Foo</li>
      <li>Bar</li>
      <li><input /></li>
    </ul>
    
  • index.scss (without stretching):

    @import "compass/reset";
    @import "compass/typography/lists/horizontal-list";
    
    body {
      background: darkgray;
    }
    
    ul {
      width: 100%;
      background: lightgray;
      @include horizontal-list;
    }
    

Question

What is an elegant way to make the last element take up the remaining horizontal space?

Details:

  • See image below for desired output.

  • Adaption of HTML code is OK, as long as it remains semantically clear.

  • The solution should work in the latest Firefox, in the latest Chrome, and in IE8-11 (JavaScript shim, if needed, is acceptable).

Desired output

feklee
  • 7,555
  • 9
  • 54
  • 72

2 Answers2

2

This one solution with only css.

HTML:

<ul>
  <li>Foo</li>
  <li>Bar</li>
  <li class="last"><input type="text" /></li>
</ul>

CSS:

ul li { float: left; list-style: none; }
ul li.last { float: none; display: block; overflow: hidden; }
ul li input { width: 100%; border: 0; box-shadow: inset 0 0 1px #000; }

Demo:

* { margin: 0; padding: 0; }
ul li { float: left; list-style: none; }
ul li.last { float: none; display: block; overflow: hidden; }
ul li input { width: 100%; border: 0; box-shadow: inset 0 0 1px #000; }
<ul>
  <li>Foo</li>
  <li>Bar</li>
    <li class="last"><input type="text" /></li>
</ul>

(Also on jsFiddle)

It should be supported by IE7+

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
drip
  • 12,378
  • 2
  • 30
  • 49
  • Thanks! The last `li` takes up the remaining space, and the `input` sets width relative to the surround block element, which is the `li`. – feklee Nov 16 '13 at 14:41
  • It would be great if you could add the HTML from the fiddle to your answer. Otherwise, I noticed, it's incomplete. – feklee Nov 18 '13 at 09:23
  • Don't see the point since it differs with only one class, that can be added as static or dynamic(with js) but that wasn't the point of the question... But it's added... – drip Nov 18 '13 at 15:35
  • Thanks! People copy and paste code. [Answering guidelines](http://stackoverflow.com/help/how-to-answer) point out that a *"target site [can be] unreachable or [go] permanently offline"*. – feklee Nov 18 '13 at 16:25
1

You can use display:table-cell (caniuse):

ul {
    width: 100%;
    background: lightgray;
}

li{
    display:table-cell;
}

ul>li:last-child, ul>li:last-child>input{
    width:100%;
}

ul>li:last-child>input{
    margin:0;
    border:0;
    background:red;
}

JSFiddle

However, :last-child is not supporter in IE8 so you'll need to target the last child with JavaScript or like this.

Community
  • 1
  • 1
Vucko
  • 20,555
  • 10
  • 56
  • 107