如何使用填充保持表格单元格内容相同?

时间:2017-01-19 00:11:42

标签: html css

我有以下CSS表。我在每个单元格中添加了左右填充。但是第一个和最后一个单元格,我删除了它们的第一个和最后一个(分别)填充。这会调整其余单元格内容的大小(可能是因为border-box)。

如何防止这种情况发生,以便所有单元格具有相同大小的元素,但我仍然可以删除第一个和最后一个单元格的“外部”填充?

.table {
  width: 100%;
  display: table;
  max-width: 1000px;
  margin-left: auto;
  margin-right: auto;
}

.cell {
  width: 20%;
  display: table-cell;
  padding: 30px;
  outline: 1px dotted blue;
  text-align: center;
  vertical-align: middle;
}

.cell:first-child {
  padding-left: 0;
}
  
.cell:last-child {
  padding-right: 0;
}

img {
  max-width: 100%;
}

h1 {
  margin-top: 2em;
  text-align: center;
  font-family: sans-serif;
  font-size: 18px;
}
<div class='table'>

  <div class='cell'>
    <img src="http://placehold.it/300x200">
  </div>
  
  <div class='cell'>
    <img src="http://placehold.it/300x200">
  </div>
  
  <div class='cell'>
    <img src="http://placehold.it/300x200">
  </div>
  
  <div class='cell'>
    <img src="http://placehold.it/300x200">
  </div>
  
  <div class='cell'>
    <img src="http://placehold.it/300x200">
  </div>
  
</div>

<h1>How do I eliminate the padding on the left and right side but keep all table-cell contents the same size</h1>

1 个答案:

答案 0 :(得分:0)

我已修复您的代码,选择第一个和最后一个孩子的内部图片然后使用css calc()方法

.cell:first-child img {
   width:calc(100% - 30px);
   float:right;
}
.cell:last-child img {
   width:calc(100% - 30px);
   float:left;
}

使用代码段

进行检查

&#13;
&#13;
.table {
   width: 100%;
   display: table;
   max-width: 1000px;
   margin-left: auto;
   margin-right: auto;
}
.cell {
   width: 20%;
   display: table-cell;
   padding: 30px;
   outline: 1px dotted blue;
   text-align: center;
   vertical-align: middle;
}
.cell:first-child {
   padding-left: 0;
}
.cell:last-child {
   padding-right: 0;
}
.cell:first-child img {
   width:calc(100% - 30px);
   float:right;
}
.cell:last-child img {
   width:calc(100% - 30px);
   float:left;
}
img {
   max-width: 100%;
}
h1 {
   margin-top: 2em;
   text-align: center;
   font-family: sans-serif;
   font-size: 18px;
}
&#13;
<div class='table'>
  <div class='cell'> <img src="http://placehold.it/300x200"> </div>
  <div class='cell'> <img src="http://placehold.it/300x200"> </div>
  <div class='cell'> <img src="http://placehold.it/300x200"> </div>
  <div class='cell'> <img src="http://placehold.it/300x200"> </div>
  <div class='cell'> <img src="http://placehold.it/300x200"> </div>
</div>
<h1>How do I eliminate the padding on the left and right side but keep all table-cell contents the same size</h1>
&#13;
&#13;
&#13;