devlights
4/12/2013 - 4:23 AM

cssで画像をボックスの中央に配置する方法

cssで画像をボックスの中央に配置する方法

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title>画像の中央配置</title>
  <style type="text/css" media="screen">
    #container {
      padding-top: 30px;      
    }

      table {
        margin-left:  auto;
        margin-right: auto;       
      }

        thead tr th {
          width: 100px;
        }

        tbody tr td {
          width:  100px;
          height: 100px;
        }

      div img {
        vertical-align: middle;
      }

    .image-panel {
      /* IE8 以降, Firefox, Chromeに対応 */
      /* (追記) IE6の場合, ほぼOKだが画像の高さがボックスと同じ場合、1px程隙間が空く・・・ */
      /* (追記) IE7の場合, ほぼOKだが100x100の画像の場合、下の罫線が消えてしまう・・・ */
      border:           solid 1px #000;
      width:            100px;
      height:           100px;
      display:          table-cell;
      text-align:       center;
      vertical-align:   middle;
      layout-grid-line: 100px;
    }
  </style>
</head>
<body>
  <div id="container">
    <table>
      <caption>幅と高さが異なる画像を常にボックス(100x100)の中央に配置</caption>
      <thead>
        <tr>
          <th>100x100</th>
          <th>100x71</th>
          <th>71x100</th>
          <th>71x71</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>
            <div class="image-panel">
              <img src="100_100.png" alt="img" />
            </div>
          </td>
          <td>
            <div class="image-panel">
              <img src="100_71.png"  alt="img" />
            </div>
          </td>
          <td>
            <div class="image-panel">
              <img src="71_100.png"  alt="img" />
            </div>
          </td>
          <td>
            <div class="image-panel">
              <img src="71_71.png"  alt="img" />
            </div>
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</body>
</html>