CSS 使表格单元格成为正方形
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22835430/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Make table cells square
提问by Ganesh Bhosle
How to ensure that each cell of table should become squarewithout using fixed sizes? And be responsivewhen they change width.
如何在不使用固定大小的情况下确保表格的每个单元格都应该变成正方形?并在他们改变宽度时做出响应。
table {
width: 90%;
}
td {
width: 30%;
}
tr {
/** what should go here? **/
}
<table>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td>4</td>
<td>5</td>
<td>6</td>
</tr>
<tr>
<td>7</td>
<td>8</td>
<td>9</td>
</tr>
<table>
回答by web-tiki
You can use the technique described in: Grid of responsive squares.
您可以使用中描述的技术:响应方块的网格。
Adapted to your usecase with a table and square table cells, it would look like this:
使用表格和方形表格单元格适应您的用例,它看起来像这样:
table {
width: 90%;
}
td {
width: 33.33%;
position: relative;
}
td:after {
content: '';
display: block;
margin-top: 100%;
}
td .content {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
background: gold;
}
<table>
<tr>
<td><div class="content">1</div></td>
<td><div class="content">1</div></td>
<td><div class="content">1</div></td>
</tr>
<tr>
<td><div class="content">1</div></td>
<td><div class="content">1</div></td>
<td><div class="content">1</div></td>
</tr>
<tr>
<td><div class="content">1</div></td>
<td><div class="content">1</div></td>
<td><div class="content">1</div></td>
</tr>
<table>
回答by Stephan Kulla
Here is my code: http://jsfiddle.net/vRLBY/1/
这是我的代码:http: //jsfiddle.net/vRLBY/1/
The key is to use:
关键是使用:
td { width: 33%; padding-bottom: 33%; height: 0; }
td div { position: absolute }
because padding-bottom
is defined in terms of the width. More information: http://absolide.tumblr.com/post/7317210512/full-css-fluid-squares
因为padding-bottom
是根据宽度定义的。更多信息:http: //absolide.tumblr.com/post/7317210512/full-css-fluid-squares
Note:Previously I posted a not working code (see here). Thanks to @web-tiki for reporting the bug ;-)
注意:以前我发布了一个不起作用的代码(见这里)。感谢@web-tiki 报告错误;-)
回答by SOReader
If someone's looking for a solution that does not require fixed width
property (even in percentage), here's what I came up with based on above answers and the linkfrom approved answer:
如果有人正在寻找不需要固定width
属性(即使是百分比)的解决方案,以下是我根据上述答案和已批准答案中的链接提出的:
td {
height: 0;
&:after, &:before {
content: '';
display: block;
padding-bottom: calc(50% - 0.5em);
}
}
It's kinda lame but it kills two birds with one stone:
这有点蹩脚,但它可以用一块石头杀死两只鸟:
- does the trick
- makes content aligned vertically
- 有诀窍
- 使内容垂直对齐