簡體   English   中英

CSS 表格單元格等寬

[英]CSS table-cell equal width

我在表格容器中有不確定數量的表格單元格元素。

<div style="display:table;">
  <div style="display:table-cell;"></div>
  <div style="display:table-cell;"></div>
</div>

是否有一種純 CSS 方法可以使表格單元格的寬度相等,即使它們中有不同大小的內容?

擁有最大寬度需要知道我認為你有多少個單元格?

這是一個不確定數量的單元格的工作小提琴: http : //jsfiddle.net/r9yrM/1/

您可以為每個父div表格)固定寬度,否則它將像往常一樣為 100%。

訣竅是使用table-layout: fixed; 和每個單元格上的一些寬度來觸發它,這里是 2%。 這將觸發另一個表 algorightm,瀏覽器非常努力地遵守指示的維度。
請使用 Chrome(和 IE8- 如果需要)進行測試。 最近的 Safari 沒問題,但我不記得這個技巧與它們的兼容性。

CSS(相關說明):

div {
    display: table;
    width: 250px;
    table-layout: fixed;
}

div > div {
    display: table-cell;
    width: 2%; /* or 100% according to OP comment. See edit about Safari 6 below */
}

編輯(2013 年):注意 OS X 上的 Safari 6,它有table-layout: fixed; 錯誤(或者可能只是不同,與其他瀏覽器非常不同。我沒有校對 CSS2.1 REC 表格布局;))。 准備好迎接不同的結果。

HTML

<div class="table">
    <div class="table_cell">Cell-1</div>
    <div class="table_cell">Cell-2 Cell-2 Cell-2 Cell-2Cell-2 Cell-2</div>
    <div class="table_cell">Cell-3Cell-3 Cell-3Cell-3 Cell-3Cell-3</div>
    <div class="table_cell">Cell-4Cell-4Cell-4 Cell-4Cell-4Cell-4 Cell-4Cell-4Cell-4Cell-4</div>
</div>​

CSS

.table{
    display:table;
    width:100%;
    table-layout:fixed;
}
.table_cell{
    display:table-cell;
    width:100px;
    border:solid black 1px;
}

演示。

僅在display: table-cell元素中使用max-width: 0對我有用:

 .table { display: table; width: 100%; } .table-cell { display: table-cell; max-width: 0px; border: 1px solid gray; }
 <div class="table"> <div class="table-cell">short</div> <div class="table-cell">loooooong</div> <div class="table-cell">Veeeeeeery loooooong</div> </div>

代替

  <div style="display:table;">
    <div style="display:table-cell;"></div>
    <div style="display:table-cell;"></div>
  </div>

  <table>
    <tr><td>content cell1</td></tr>
    <tr><td>content cell1</td></tr>
  </table>

看看試圖讓 div 像表格一樣執行的所有問題。 他們不得不添加 table-xxx 來模仿表格布局

支持表格並且在所有瀏覽器中都能很好地工作。 為什么要拋棄他們? 他們必須模仿他們的事實證明他們做得很好。

在我看來,使用最好的工具來完成這項工作,如果你想要表格數據或類似於表格數據表的東西就可以了。

我知道很晚的回復,但值得發聲。

這對每個人都有效

 <table border="your val" cellspacing="your val" cellpadding="your val" role="grid" style="width=100%; table-layout=fixed"> <!-- set the table td element roll attr to gridcell --> <tr> <td roll="gridcell"></td> </tr> </table>

這也適用於迭代創建的表數據

這可以通過將 table-cell 樣式設置為width: auto和 content empty 來完成。 列現在等寬,但沒有內容。

要將內容插入單元格,請使用 css 添加一個div

position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;

您還需要添加position: relative對於單元格。

現在您可以將實際內容放入上面談到的 div 中。

https://jsfiddle.net/vensdvvb/

干得好:

http://jsfiddle.net/damsarabi/gwAdA/

您不能使用 width: 100px,因為顯示的是表格單元格。 但是,您可以使用 Max-width: 100px。 那么你的盒子永遠不會超過 100px。 但您需要添加 overflow:hidden 以確保連接不會流到其他單元格。 如果您希望保持高度不增加,您還可以添加 white-space: nowrap 。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM