【问题标题】:clickable div with image centered vertically and horizontally可点击的 div,图像垂直和水平居中
【发布时间】:2011-06-21 08:37:17
【问题描述】:

我需要创建一个可点击的 div,其图像(大小可变,但小于 div)在 div 内水平和垂直居中。

我使 div 可点击

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

但似乎无法将图像垂直居中。

【问题讨论】:

  • 你尝试过#image-box img {margin:auto;text-align:center} 吗?

标签: html css


【解决方案1】:

尝试按照 cmets 中的说明调整 a 元素的宽度和高度:

<!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>

注意事项: 边框仅用于可视化调试,您可以随时删除。

这里的诀窍是您使用具有固定宽度和高度的绝对定位 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>

【讨论】:

  • 有趣的建议,但我事先不知道图片的高度和宽度。
猜你喜欢
  • 2017-08-04
  • 2013-05-18
  • 2015-08-29
  • 1970-01-01
  • 2013-04-05
  • 2012-05-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多