1

My code is:

<label>Something:</label> <span>Some Value</span>
<br/>

<label>Something:</label> <span>Some Value</span>
<br/>

The <label> has a fixed width.

Output:

Something:  Some Value
Something:  Some Value

However if Some Value is quite long it wraps incorrectly

Something:  Some Value
Something:  Some Value Some
Value Some

Is there a nice solution to this so it lines up as you'd expect? I'm making rather a large table of data and it's not possible to predict which values will span multiple lines in advance.

Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189
NibblyPig
  • 51,118
  • 72
  • 200
  • 356

3 Answers3

3

If you can fix the width of both elements apply display:block and float:left. This will create a column like appearance and cause the span to wrap within the column.

CSS:

   label, span{
        float: left;
        width: 150px; /* Adjust widths to fit your needs */
    }

   br{ clear: both;}

HTML

<label>Something:</label> <span>Some Value</span>
<br/>

<label>Something:</label> <span>Some Value that is alot longer and wraps</span>

JS Fiddle: http://jsfiddle.net/gvPdQ/

Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189
  • 1
    You don't need to use `display:block` and `float:left` both. [DEMO](http://jsfiddle.net/tewathia/gvPdQ/1/) – tewathia Dec 17 '13 at 10:33
  • @tewathia Interesting, it appears that when you float the element the browser automatically applies `display:block`. See: http://jsfiddle.net/gvPdQ/2/ Do you know if this occurs cross browser? – Kevin Bowersox Dec 17 '13 at 10:37
  • 1
    @KevinBowersox: http://stackoverflow.com/questions/6372021/redundant-css-rules-ie-float-displayblock – Salman A Dec 17 '13 at 10:39
  • @SLC For multiple rows you can wrap the `span` and `label` tags. See: http://jsfiddle.net/hx27k/1/ or you can add `clear:both` to the `br` tags: http://jsfiddle.net/hx27k/2/ – Kevin Bowersox Dec 17 '13 at 13:40
1

If you are allowed to tweak you markup I have the following solution. Requires that labels are fixed width; the spans fill remaining space.

HTML

<div class="row">
    <label>Something:</label> <span>Some Value</span>
</div>
<div class="row">
    <label>Something:</label> <span>Some Value Some Value Some Value Some Value Some Value Some Value Some Value Some Value Some Value Some Value</span>
</div>

CSS

.row {
    overflow: hidden;
}
.row label {
    display: block;
    float: left;
    width: 200px;
}
.row span {
    display: block;
    margin-left: 210px; /* equal to label width plus some gap */
}

Demo here

Salman A
  • 262,204
  • 82
  • 430
  • 521
0

If you are making “a large table of data”, use a table element, e.g.

<table>
<tr><th>Something <td>Some value
<tr><th>Something <td>Some value
...
</table>

You can still set a fixed width on Something, but you need not.

It is incorrect to use the label element for anything else than labelling a labellable element (normally, a control, i.e. form field).

Jukka K. Korpela
  • 195,524
  • 37
  • 270
  • 390