我需要创建一个可点击的div与图像(可变大小,但小于div)在div中水平和真实地居中。可点击的div与图像垂直和水平居中
我做了DIV可点击与
#image-box a { display: block; height: 100%; width: 100%; }
,但似乎无法垂直居中的图像。
我需要创建一个可点击的div与图像(可变大小,但小于div)在div中水平和真实地居中。可点击的div与图像垂直和水平居中
我做了DIV可点击与
#image-box a { display: block; height: 100%; width: 100%; }
,但似乎无法垂直居中的图像。
试试你的一个元素的这种调节宽度和高度在评论中解释说:
<!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>
有趣的建议,但我不知道事先的图像的高度和宽度。 – Neil
@Neil使用jquery更新:支持动态图像大小 – microspino
非常好 - 感谢这个解决方案! – Neil
你是否已经尝试#图像框IMG {保证金:汽车;文本对齐:中心}? – microspino