2011-06-21 24 views
0

div内に水平と真ん中の両方を中心とする画像(可変サイズですがdivより小さい)でクリック可能なdivを作成する必要があります。クリック可能div画像を垂直方向と水平方向の中心に合わせる

私は

#image-box a { display: block; height: 100%; width: 100%; } 

でのdivクリッカブルをしたが、垂直方向に画像を中央に見えることはできません。コメントで説明したように

+0

はすでに#画像ボックスIMGみました{マージン:自動;テキスト整列:センター}? – microspino

答えて

1

は、あなたの要素のこの調整幅と高さを試してみてください。

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" 
    "http://www.w3.org/TR/html4/strict.dtd"> 
<html lang="en"> 
<head> 
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 
    <title>Centered Clickable Image</title> 
    <style type="text/css" media="screen"> 
    #image-box { 
      position:absolute; 
      top:0; bottom:0; left:0; right:0; 
      margin:auto; 
      border: 1px solid #999; 
      text-align: center; 
      } 

    #image-box a {display:block; position:absolute; 
      top:0; bottom:0; left:0; right:0; 
      margin:auto; text-align: center; 
      } 

    /* insert the same width and height of your-nice-img.png */ 
    #image-box a {width:339px; height:472px; border: 2px solid red;} 
</style> 
</head> 
<body>  
    <div id="image-box"> 
     <a href="#"> 
      <img src="your-nice-image.png" alt="image to center"/> 
     </a> 
    </div> 
</body> 
</html> 

NOTES: 国境が唯一の視覚的デバッグのために必要とされている、あなたはいつでも削除することができます。

ここでは、固定幅と高さを持つ絶対配置div(#image-box)を使用します。

もしゼロ#image-box a頂部および底部位置を設定した場合、それは一定の高さを有しているのでルールmargin:autoは、(縦軸)の中間位置に#image-box a要素を置きます。

することができますかjQueryのを使用してそれを解決したい場合は、この試してみてください。

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> 
<html lang="en"> 
<head> 
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 
    <title>Centered Image</title> 
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> 

    </head> 
    <body> 
     <div id="image-box"> 
      <a href="#"> 
       <img src="canning.png" alt="image to center"/> 
      </a> 
     </div> 

    <script type="text/javascript" charset="utf-8"> 
    $(document).ready(function(){ 
     $(window).resize(function(){ 
      $('#image-box a').css({ 
       position:'absolute', 
       left: ($(window).width() - $('#image-box a img').outerWidth())/2, 
       top: ($(window).height() - $('#image-box a img').outerHeight())/2 
      }); 
     }); 
      // first run 
     $(window).resize(); 
    }); 
    </script> 
    </body> 
    </html> 
+0

興味深い提案ですが、画像の高さと幅はあらかじめわかりません。 – Neil

+1

@Neilはjqueryを使用して更新されました:動的画像サイズのサポート – microspino

+0

このソリューションには感謝します! – Neil

関連する問題