td内的图像是td的高度

时间:2018-04-24 12:38:57

标签: html css

我想要的是当图像不存在时图像与td的高度相同,即300px,而不是图像src的高度。我无法指定图像,td或表的高度,因为父div表示响应容器的高度。我花了太长时间在这上面并且尝试了很多东西,并且出于某种原因,图像始终坚持完全高度。

<div style='height:300px;width:300px;'>
  <table style='height:100%;width:100%;'>
    <tr>
      <td>
        <img style='height:100%;width:100%;' src='https://placehold.it/1920x1200'>
      </td>
    </tr>
 </table>
</div>

2 个答案:

答案 0 :(得分:0)

尝试使用CSS而不是内联样式。这有助于保持代码更加灵活。我已将heightwidth设置为auto,将max-heightmax-width设置为100%,以便包含图片在表格单元格内部,但也正确缩放。

.table-container {
  height: 300px;
  width: 300px;
  padding: 5px;
  border: 1px solid red;
}

table td {
  border: 1px solid blue;
  padding: 0;
}

table td img {
  display: block;
  width: auto;
  height: auto;
  max-width: 100%;
  max-height: 100%;
}
  <div class='table-container'>
    <table>
      <tr>
        <td>
          <img src='https://placehold.it/1920x1200' />
        </td>
      </tr>
   </table>
  </div>

答案 1 :(得分:-1)

  

试试这个,添加“overflow:hidden; position:relative;”父母和“位置:绝对;”对孩子

 <div style='height:300px;width:300px;'>
  <table style='height:100%;width:100%; overflow: hidden;position: relative;'>
    <tr>
      <td style='position: absolute;'>
        <img style='height:100%;width:100%;' src='https://placehold.it/1920x1200'>
      </td>
    </tr>
 </table>
</div>

输出屏幕

enter image description here

相关问题