像桌子一样但是与CSS对齐?

时间:2011-09-08 14:30:33

标签: html css layout

是否可以像桌子一样对齐以下两行?第一行是h2,因为它是标题,其余是列表。第一列应该很宽,但其余部分可以与文本内部一样宽。列必须填充div的宽度。

<div>
<h2 class="header1">
<span class="span1">one</span>
<span class="span2">two</span>
<span class="span3">three</span>
<span class="span4">four</span>
</h2>
<ul><li>
<span class="span5">five</span>
<span class="span6">six</span>
<span class="span7">seven</span>
<span class="span8">eight</span>
</li></ul>
</div>
div {width: 500px;}
h2 span, li span {float: left; width: auto; white-space: nowrap;}

示例:

Example

3 个答案:

答案 0 :(得分:11)

HTML

<div class="table-like">
  <div>
    <span>one</span>
    <span>two</span>
    <span>three</span>
    <span>four</span>
  </div>
  <div>
    <span>five</span>
    <span>six</span>
    <span>seven</span>
    <span>eight</span>
  </div>
</div>

CSS

.table-like {
  display: table;
  width: 500px;
}

.table-like div { 
  display: table-row;
}

.table-like div span { 
  display: table-cell;
}

/* add borders */
.table-like,
.table-like div span {
  border: 1px solid black;  
}

/* bold on 1st row */
.table-like div:nth-child(1) {
  font-weight: bold;
}

jsFiddle Demo

答案 1 :(得分:4)

老实说,如果您要显示表格数据,请使用表格。表格没有任何问题,只有当您使用它们来定位非表格内容时。如果您需要帮助格式化表格,请编辑您的问题。

答案 2 :(得分:0)

尝试使用display:inline-block:

h2{display: inline-block; margin:0 padding:0; min-width: 300px}/*use min-width what you want*/
ul, ul li{display: inline-block; margin:0; padding: 0;}