实现图片水平垂直居中
代码如下:
<html>
<head></head>
<style type="text/css">
.div1{
width: 500px;
height: 500px;
background-color: red;
position: absolute;
}
.div2{
width: 300px;
height: 200px;
background-color: blue;
position: absolute;
top: 50%;
left: 50%;
margin-top: -100px;
margin-left: -150px;
overflow: hidden;
}
img{
width: 0;
}
</style>
<script type="text/javascript" src="jquery-2.1.1.min.js"></script>
<body>
<div class="div1">
<div class="div2"><img src="c.jpg"><div>
</div>
<script type="text/javascript">
$(function() {
var $img = $("img");
$img.css("width","100%");
var height = $img.css("height");
height = height.slice(0,-2);
if (height < 200) {
$img.css("height","100%");
};
})
</script>
</body>
</html>
重要的是js那一段。效果示例如图,第一个div设置长宽,第二个div设置一定的宽度,将图片放到里面去,overflow:hidden,这样无论图片是何种格式的,如果图片太小就填充整个div,如果太大就hidden掉。为了让图片能够显示的时候不变形,所以设置成weidth:100%,这样的话可能出现问题是当width:100%的时候,高度小于第二个div的高度200px,所以此时需要判断下图片高度是否大于200px,如果小于那就将高度设置成100%。楼主本来想着只用css,不用js是否能实现的,搞了半天不行,无奈选择用js动态实现这样的过程,泪奔泪奔,泪奔.
然后一个知识点需要记录一下,margin-top.margin-left设置成50%的时候,它的值始终只是父级元素的宽的50%,记住,是父级的width,如果父级width是500,height是200,设置子级元素margin-top:50%,margin-left:50%,那么得到的将是margin-top:250,margin-left:250.