<%@ Page Language="C#" %>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
Image imgTest = new Image();
imgTest.ID = "toot2008Img" ;
imgTest.CssClass = "cssImgContainer";
imgTest.ImageUrl = "~/productImages/CoffeeTable/20090327/coffeeTable_05.jpg";
imgTest.PreRender += new EventHandler(imgProd_PreRender);
divImgTest.Controls.Add(imgTest);
}
void imgProd_PreRender(object sender, EventArgs e)
{
Image imgProd = (Image)sender;
float fImgW = 0f;
float fImgH = 0f;
try
{
System.Drawing.Image img = System.Drawing.Image.FromFile(Server.MapPath(imgProd.ImageUrl.ToString()));
fImgW = img.Width;
fImgH = img.Height;
img.Dispose();
}
catch (Exception ex)
{
imgProd.ToolTip = "Image File not found...";
return;
}
float fImgRate = fImgW / fImgH;
float oriRate = 700f / 690f;
if (fImgRate >= oriRate)
{
imgProd.Width = 225;
int thisH = (int)(fImgH * 225 / fImgW);
imgProd.Height = thisH;
imgProd.CssClass = "cssImgTopPadding" + ((222 - thisH) / 2 / 12).ToString();
}
else
{
imgProd.Width = (int)(fImgW * 222 / fImgH);
imgProd.Height = 222;
}
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>toot2008@126.com(W3C标准) ASP.NET + CSS 设置 图片等比放缩、水平居中、垂直(竖直)居中 </title>
<style type="text/css">
.cssImgContainer{
float:left;
height:100%;
width:100%;
text-align:center ;
overflow:hidden;
text-overflow : ellipsis ;
}
.cssImgOriStyle{
border:solid 1px #ddd;
/*此处添加其它图片样式*/
}
/*下面是加成样式,靠设置padding-top来竖直居中图片*/
.cssImgTopPadding0{ padding-top:0em; }
.cssImgTopPadding1{ padding-top:1em; }
.cssImgTopPadding2{ padding-top:2em; }
.cssImgTopPadding3{ padding-top:3em; }
.cssImgTopPadding4{ padding-top:4em; }
.cssImgTopPadding5{ padding-top:5em; }
.cssImgTopPadding6{ padding-top:6em; }
.cssImgTopPadding7{ padding-top:7em; }
.cssImgTopPadding8{ padding-top:8em; }
.cssImgTopPadding9{ padding-top:9em; }
</style>
</head>
<body>
<form id="form1" runat="server">
<div id="divImgTest" class="cssImgContainer" runat="server">
</div>
</form>
</body>
</html>