2015年4月

先看看效果

未标题-1.jpg

需求

  1. 图片以背景的形式铺满整个屏幕,不留空白区域
  2. 保持图像的纵横比(图片不变形)
  3. 图片居中
  4. 不出现滚动条

最简单的实现

html{
	height: 100%;
	background: url(1.jpg);
	background-size: cover;
}

但是使用该方法后,当屏幕比例和图片比例不一样时,背景的右边或下边会隐藏掉,不符合我们的图片居中的需求。因此我们再结合JS进行偏移量的计算:

完整代码

<!DOCTYPE html>
<html>
<head>
	<style>
		* {
			padding: 0;
			margin: 0;
		}

		html, body {
			height: 100%;
		}

		.demo {
			height: inherit;
			background: url(http://imgs.meimeinice.com/imgs/f6964325bad452acd582f58db7ce2e9d.jpg) no-repeat;
			background-size: cover;
		}
	</style>
	<script src="http://libs.baidu.com/jquery/1.9.1/jquery.min.js"></script>
	<meta charset="utf-8">
	<title>background</title>
</head>
<body>
	<div class="demo"></div>
</body>
<script>
	$(function () {
		var imgSize = {},
			img = new Image(),
			url = $('.demo').css('background-image').substr(5);

		img.src = url.substr(0, url.length - 2);;
		img.onload = function () {
			imgSize = {
				w: img.width,
				h: img.height
			};
			$(window).trigger('resize');
		};

		$(window).on('resize', function () {
			if (!imgSize) {
				return;
			}
			var node = $('.demo'),
				nodeWidth = node.width(),
				nodeHeight = node.height(),
				imgRate = imgSize.w / imgSize.h,
				nodeRate = nodeWidth / nodeHeight,
				offset;

			//图片比容器的比率大,容器的宽度较窄,图片向左隐藏
			if (imgSize.w > nodeWidth && imgRate > nodeRate) {
				offset = (nodeWidth - imgRate * nodeHeight) / 2;
				node.css('backgroundPosition', offset + 'px 0');
			}

			//向上隐藏
			if (imgSize.h > nodeHeight && imgRate < nodeRate) {
				offset = (nodeHeight - nodeWidth / imgRate) / 2;
				node.css('background-position', '0 ' + offset + 'px');
			}
		});

	});
</script>
</html>

回归简单

由于前面写CSS的时候没有想到背景居中,而去写了一大段的JS的配合,结果最近发现在用cover的同时再配合背景居中就能搞定:

html{
	height: 100%;
	background: url(1.jpg) no-repeat center;
	background-size: cover;
}