简体   繁体   中英

How do I align a <label> with a <span> when the <span> sometimes goes onto multiple lines?

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.

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/

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

If you are making “a large table of data”, use a table element, eg

<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, ie form field).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM