显示:表格单元格宽度(百分比)

时间:2015-04-19 18:25:55

标签: css

我有这个CSS代码:

section.products {
    display: table;
    width: 100%;    
    table-layout: fixed;
}

section.products > article {
    display: table-cell;
    width: 33%;
}

这不能正确设置宽度(每篇文章的宽度都会自动设置为适合所有文章元素到一行)。但是当我设置<article style="width: 33%;">(内联声明)时,宽度是正确的。怎么了?谢谢你的任何建议。

编辑(演示):https://jsfiddle.net/Lt822wkq/

2 个答案:

答案 0 :(得分:1)

如果您有三个子元素,则表格布局有效。

如果您只有一个子元素,它将展开以填充整个可用宽度,即使您为宽度应用内联样式,请参阅示例2和3.

但是,如果将display: block设置为单个子article,则宽度将为33%,但这是因为该元素不再像表格单元格那样。

&#13;
&#13;
section.products {
  display: table;
  width: 100%;
  table-layout: fixed;
  border: 1px dotted gray;
}
section.products > article {
  display: table-cell;
  width: 33%;
  border: 1px dotted gray;
}
section.products > article.blocky {
  display: block;
}
&#13;
<section class="products">
  <article>Article One Donec adipiscing, lorem non euismod venenatis, diam orci tincidunt magna, ut interdum magna arcu vel elit. Nunc molestie lacus non urna eleifend mattis. Praesent ipsum nulla, tempor malesuada lacinia quis, elementum et tellus. </article>
  <article>Article Two Donec adipiscing, lorem non euismod venenatis, diam orci tincidunt magna, ut interdum magna arcu vel elit. Nunc molestie lacus non urna eleifend mattis. Praesent ipsum nulla, tempor malesuada lacinia quis, elementum et tellus. </article>
  <article>Article Three Donec adipiscing, lorem non euismod venenatis, diam orci tincidunt magna, ut interdum magna arcu vel elit. Nunc molestie lacus non urna eleifend mattis. Praesent ipsum nulla, tempor malesuada lacinia quis, elementum et tellus. </article>
</section>

<h2>Example 2</h2>
<section class="products">
  <article>Article One Donec adipiscing, lorem non euismod venenatis, diam orci tincidunt magna, ut interdum magna arcu vel elit. Nunc molestie lacus non urna eleifend mattis. Praesent ipsum nulla, tempor malesuada lacinia quis, elementum et tellus. </article>
</section>

<h2>Example 3</h2>
<section class="products">
  <article style="width: 33%;">Article One Donec adipiscing, lorem non euismod venenatis, diam orci tincidunt magna, ut interdum magna arcu vel elit. Nunc molestie lacus non urna eleifend mattis. Praesent ipsum nulla, tempor malesuada lacinia quis, elementum et tellus. </article>
</section>

<h2>Example 4</h2>
<section class="products">
  <article class="blocky" style="width: 33%;">Article One Donec adipiscing, lorem non euismod venenatis, diam orci tincidunt magna, ut interdum magna arcu vel elit. Nunc molestie lacus non urna eleifend mattis. Praesent ipsum nulla, tempor malesuada lacinia quis, elementum et tellus. </article>
</section>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

在样式表中设置适用于每个article {width: 33%;}元素的<article>。但是,如果您使用仅适用于该元素的内联样式<article style="width: 33%;">

在您的演示中,共有4个表格单元格,您将每个单元格设置为33%,由于总宽度超过100%,因此无法正常工作。