用纯CSS实现容器内图片上下左右居中


一直以来,大家都知道,DIV容器内设置 text-align:center 即可让图片居中,但是DIV内默认的图片是上对齐,不会上下居中,如果想要实现这样的效果,JS判断是比较麻烦的,因为DIV容器内的图片高度是不一定的,那么只有用table了,我想大多数人事不愿意这么做的,那么怎么办呢,还是用CSS控制下吧

其实早就在找这样的代码,今天终于自己试着写了一份出来,屌丝们可以自己分析下原理,其实很简单
如果你之前也不会,那么希望对你有所帮助

复制代码
代码如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>纯css实现div容器内图片上下左右居中效果-柯乐义</title>
<style type="text/css">
*{ margin:0; padding:0; list-style:none;}
img{ border:none;}
.main{ width:600px; height:400px; margin:100px auto;text-align:center;vertical-align:middle;display:block;position:relative; background:#ddd;}
.main a{display:table-cell;vertical-align:middle;width:600px; height:400px; }
.main a img{max-width:600px;max-height:400px; }
</style>
</head>
<body>
<div class="main">
<a href="http://keleyi.com/a/bjac/wynnj5xc.htm" target="_blank"><img src="http://keleyi.com/keleyi/phtml/picnext/images/k06.jpg" alt="柯乐义" /></a>
</div>
</body>
</html>

兼容IE8,火狐,Chrome,Opera等浏览器

图片在各种分辨率下未知的容器内上下左右居中(需要用到jquery)

DIV:


复制代码
代码如下:

<div class="pic_conent">
<div class=" fn-pr pic_layer">
<!--图片文字介绍透明层-->
<section class="bg text_layer_home p10 font-yahei fn-bc">
<h2 class="f14 fefefe">${pic.desc}</h2>
<aside class="f12 bbb">
<c:if test="${not empty pic.poi}">
<span class="scenery fn-fl">${pic.poi}</span>
</c:if>
<span class="fn-fr mt10">by ${pic.username}</span>
</aside>
</section>
<img src="${pic.picUrl}" width="320" height="420" />
</div>
</div>

CSS:


复制代码
代码如下:

.pic_conent{
height: 720px;/*这个高度会被js改掉*/
text-align: center;
display: table-cell;
vertical-align: middle;
}
.pic_layer{text-align:center; width:100%; display:inline-block; vertical-align:middle;}

jquery:


复制代码
代码如下:

$(function() {
var surH = $(window).height();
$(".pic_conent").height(surH);
window.onresize=function(){
var surH = $(window).height();
$(".pic_conent").height(surH);
}


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3