CSS 讓圖片垂直居中的程式碼:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml" lang="zh-CN">
<head>
<title>圖片垂直居中</title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<style type="text/css" media="all">
div, img { margin: 0; padding: 0; border: 0; }
#content {
width: 303px;
height: 404px;
background: #F63;
color: #000;
font: 12px Arial, Helvetica, sans-serif;
position: relative;
}
#content[id] { display: table; position: static; }
#middle { position: absolute; left: 0; top: 50%; }
#middle[id] { display: table-cell; vertical-align: middle; position: static; }
#inner { position: relative; left: 0; top: -50%; }
</style>
</head>
<body>
<div id="content">
<div id="middle">
<div id="inner">垂直居中<br />
<img src="logo.gif" alt="logo" title="logo" />
</div>
</div>
</div>
</body>
</html>
CSS 讓圖片底端對齊的程式碼:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml" lang="zh-CN">
<head>
<title>圖片底端對齊</title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<style type="text/css" media="all">
div, img { margin: 0; padding: 0; border: 0; }
#content {
width: 303px;
height: 404px;
background: #F63;
color: #000;
font: 12px Arial, Helvetica, sans-serif;
position: relative;
}
#content div { position: absolute; left: 0; bottom: 0; }
</style>
</head>
<body>
<div id="content">
<div>底端對齊<br />
<img src="logo.gif" alt="logo" title="logo" />
</div>
</div>
</body>
</html>
第一段程式碼善用 display: table-cell 搭配 vertical-align: middle,並以 50% 位移技巧抵消自身高度,讓內容在容器中精準垂直居中;第二段則改以絕對定位配合 bottom: 0,把圖片穩定地貼齊容器底端。兩種寫法都不依賴固定像素的魔法數字,能從容應對不同尺寸的圖片。