首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >可点击的div,图像垂直和水平居中

问可点击的div,图像垂直和水平居中
EN

Stack Overflow用户
提问于 2011-06-21 16:37:17
回答 1查看 866关注 0票数 0

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

我将div设置为可点击

代码语言:javascript
复制
    #image-box a { display: block; height: 100%; width: 100%; }

但似乎不能垂直居中图像。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-06-21 16:53:01

尝试调整a元素的宽度和高度,如评论中所述:

代码语言:javascript
复制
<!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顶部和底部位置设置为0,则规则margin:auto会将#image-box a元素放在中间位置(在垂直轴上),因为它具有固定的高度。

如果您可以或喜欢使用jQuery解决此问题,请尝试以下操作:

代码语言:javascript
复制
<!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>
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6422492

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档