[英]clickable div with image centered vertically and horizontally
我需要創建一個可點擊的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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.