网页前端设计

http://www.86y.org

搜索文章

垂直居中及容器内图片垂直居中的CSS解决方法

用声音读出全文关注我吧
 2010/12/22 12:05:24 阅读次数:9266

Div与CSS布局,最让人头疼的就是容器内的东西如何垂直居中的问题,我在做站时也遇到,查了一下资料,总结出以下居中办法,兼容IE与及 Firefox!

方法一

<style type="text/css">
<!-- 
* {margin:0;padding:0}
div {
  width:500px;
  height:500px;
  border:1px solid #666;
  overflow:hidden;
  position:relative;
  display:table-cell;
  text-align:center;
  vertical-align:middle
}
div p {
  position:static;
  +position:absolute;
  top:50%
  }
img {
  position:static;
  +position:relative;
  top:-50%;left:-50%;
  }
-->
</style>
<div><p><img src="http://www.google.com/intl/en/images/logo.gif" /></p></div>

 

方法二

<!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>div里面图片垂直居中的几个例子</title>
<style type="text/css">
<!-- 
body {
  margin:0;padding:0
}
div {
  width:500px;
  height:500px;
  line-height:500px;
  border:1px solid #666;
  overflow:hidden;
  position:relative;
  text-align:center;
}
div p {
  position:static;
  +position:absolute;
  top:50%
}
img {
  position:static;
  +position:relative;
  top:-50%;left:-50%;
  vertical-align:middle
}
p:after {
  content:".";font-size:1px;
  visibility:hidden
}
-->
</style>
</head>
<body>
<div><p><img src="http://www.google.com/intl/en/images/logo.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.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>div里面图片垂直居中的几个例子</title>
<style type="text/css">
<!-- 
* {margin:0;padding:0}
div {
  width:500px;
  height:500px;
  line-height:500px;
  border:1px solid #666;
  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%;
  vertical-align:middle
}
-->
</style>
</head>
<body>
<div><p><img src="http://www.google.com/intl/en/images/logo.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.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>div里面图片垂直居中的几个例子</title>
<style type="text/css">
<!-- 
* {margin:0;padding:0;}
div {
  width:500px;border:1px solid #666;
  height:500px;
  background:url("http://www.google.com/intl/en/images/logo.gif") center no-repeat
}
-->
</style>
</head>
<body>
<div></div>
</body>
</html>

大家有什么问题或技术上的想法可以在此与大家分享,也可以加入前端爱好者QQ群(141999928)一起学习进步:【幸凡前端技术交流群】
如需转载请注明出处:http://www.86y.org/art_detail.aspx?id=73【垂直居中及容器内图片垂直居中的CSS解决方法】幸凡学习网
0

如果您觉得本文的内容对您的学习有所帮助,捐赠与共勉,支付宝(左)或微信(右)

阅读全文内容关闭