三款css div 圖片垂直置中代碼

來源:互聯網
上載者:User
 代碼如下 複製代碼

cssbox{
 /* 非ie核心瀏覽器識別垂直置中 */
 display:table-cell;
 vertical-align:middle;
 /* ie核心瀏覽器識別垂直置中 */
 *display:block;
 /* 約為高度的0.873,200*0.873 約為175 */
 *font-size:175px;
 text-align:center;
 width:200px;
 height:200px;
}
.cssbox img{
 vertical-align:middle;
}

方法二

 代碼如下 複製代碼

<!doctype html public "-//w3c//dtd xhtml 1.0 strict//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>www.111cn.net</title>
<style type="text/css">
<!--
* {margin:0;padding:0}
div {
 width:500px;
 height:500px;
 line-height:500px;
 border:1px solid #ccc;
 overflow:hidden;
 position:relative;
 text-align:center;
}
div p {
 position:static;
 +position:absolute;
 top:50%;
 vertical-align:middle
}
img {
 position:static;
 +position:relative;
 top:-50%;left:-50%;
 width:200px;
 height:90px;
 vertical-align:middle
}
-->
</style>
</head>
<body>
<div><p><img src="/skins/logo3.gif" /></p></div>
</body>
</html>

方法三

 代碼如下 複製代碼

<!doctype html public "-//w3c//dtd xhtml 1.0 strict//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-strict.dtd">
<html xmlns="http://www.111cn.net/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=gb2312" />
<title>div+css圖片垂直置中</title>
<style type="text/css">
*{ margin:0; padding:0;}
.imgbox{ width:400px; height:400px; margin:30px; border:1px solid #ddd; text-align:center; line-height:400px;}
 .imgbox img{ vertical-align:middle;}
 *html .imgbox{ font-size:360px; font-family:arial;}
</style>
</head>
<body>
<div class="imgbox">
 <img src="/article/uploadfiles/200907/20090717185022273.gif" />
</div>
</body>
</html>

1.該方法實現的垂直置中效果必須在strict 模式(dtd xhtml 1.0 strict)下才會生效.

    2.對於標準瀏覽器(ff,opera,chrome,ie8…)而言.imgbox img{ vertical-align:middle;}就可以實現圖片垂直置中.

    3.對於ie7,我們可以用line-height:400px;來達到目的.

    4.剩下的ie6是用*html .imgbox{ font-size:360px; font-family:arial;}來實現的.其中360=400*90%得來的,400為容器的高度,用90%是因為容易記,其精確值為0.873.至於這個數值怎麼來的沒有具體研究…


方法三

 代碼如下 複製代碼

<!doctype html public "-//w3c//dtd xhtml 1.0 strict//en" "http://mb.111cn.net/tr/xhtml1/dtd/xhtml1-strict.dtd">
<style type="text/css">
div {
 display:table-cell;
 height:300px;
 width:500px;
 text-align:center;
 border:1px solid #000;
 vertical-align:middle
 }
</style>
<!--[if ie]>
<style type="text/css">
i {
 display:inline-block;
 height:100%;
 vertical-align:middle
 }
img {
 vertical-align:middle
 }
</style>
<![endif]-->
<div>
<i></i>
 <img src="/img/logo.gif" alt=""/>
</div>

 

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.