我需要创建一个可点击的div,其中包含一个在div中水平和垂直居中的图像(大小可变,但比div小)。
我将div设置为可点击
#image-box a { display: block; height: 100%; width: 100%; }但似乎不能垂直居中图像。
发布于 2011-06-21 16:53:01
尝试调整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顶部和底部位置设置为0,则规则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>https://stackoverflow.com/questions/6422492
复制相似问题