开发者

HTML and CSS for table-like 'Label - Value' alignment

Okay this is embarrassing. I'm almost tempted to use TABLE but I think it's wrong.

Basically, I have a page with a fieldset, that in "Edit Mode" has a bunch of inputs like so:

<label for="txtName">Address</label>
<textarea name="Name" id="txtName">
    1 The test
    AddressTown
    UK
</textarea>

When this page is in "Read Only" mode, the textarea turns into a span e.g

<label>Address</label>
<span>
    1 The test<br />
    AddressTown开发者_运维百科<br />
    UK
</span>  

I want to lay the label and value out in a tabular way so that each label is on the left with a fixed width and the input or span follows it like so:

---------------------------
Name       1 the test
           AddressTown
           UK
---------------------------

This would be a no-brainer in a TABLE:

<table>
<tr>
    <th style="width: 150px; vertical-align: top;">
        <label>Address</label>
    </th>
    <td>
        <span>
        1 The test<br />
        AddressTown<br />
        UK
        </span>
    </td>
</table>

However I have been trying to achieve this with CSS, using float on just the label and on both, but no matter what I try, I'm in one of the following scenarios:

  • The second line of the span wraps below the label
  • The span starts directly beneath the label
  • I get a nice tabular layout BUT I have to specify the width of the span, which I don't want to do.

Any ideas?


As per my comment above there is nothing wrong with using tables for a tabular layout! If however you really don't want to use tables, you can set the span to display: block and give it a margin.

<!DOCTYPE html>
<html>
    <label>Address</label>
    <span>
        1 The test<br />
        AddressTown<br />
        UK
    </span>

    <style>
        label { float: left; width: 200px; }
        span { margin-left: 200px; display: block; }
    </style> 
</html>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜