jQuery
- <style>
- html {
- height: 100%;
- }
-
- body {
- background-image: url(background.jpg);
- background-repeat: no-repeat;
- background-attachment: fixed;
- background-position: center;
- background-size: cover;
- }
- </style>
代 - <body>
- <img src="bg.jpg" id="bg-img">
- </body>
- <style>
- #bg-img {
- position: fixed;
- top: 50%;
- left: 50%;
- z-index: -99;
- }
- </style>
代
文章起原
利用方式我可以行使background-position指定片放的中心。以上面的程式例:背景片置中,以片中放的中。
若但片靠左下,以左下角放的中可以置成:
background-position: left bottom;
另外一真利用css的方式:
先一填器窗,在放入一片,片保持在完全全部的下。
markup
上面例子只能片靠上,以上方作放的中。
如果非常峙要以片中作放的中,就要加上jQuery 一下
CSS + jQuery
- <script>
- $(function () {
-
- resize_tab();
- });
-
- $(window).resize(function () {
- resize_tab();
- }).resize();
-
- function resize_tab() {
-
- var viewportWidth = $(window).innerWidth();
- var viewportHeight = $(window).innerHeight();
-
- var width = $('#bg-img').width();
- var height = $('#bg-img').height();
-
-
- if ((viewportWidth / viewportHeight) > (width / height)) {
-
- $('#bg-img').css({
- 'width': '100%',
- 'height': 'auto',
- 'margin-left': 0 - width / 2,
- 'margin-top': 0 - height / 2
- });
-
-
- } else {
- $('#bg-img').css({
- 'width': 'auto',
- 'height': '100%',
- 'margin-left': 0 - width / 2,
- 'margin-top': 0 - height / 2
- });
- }
- }
- </script>
代 今天我要跟人人分享作版配景的方式。
此刻先肯定一下我的需求:
片必需恰好填器不能留有,也不克不及因片太大而泛起。
片可以跟著器尺寸主放。
片必比,不能形。
要告竣上面的需求,我有以下的方式可以使用
利用CSS3 background-size 性
background-size 是css3 的性,用界配景片的尺寸。使用上可以直接指定的值或是放的比例;指定"contain"可靠山片主放到填容域的最大尺寸;指定"cover"可以背景片主放到容域的最小尺寸。可以考w3c background-size的
因我而今要做的是完整覆器的景片,所以要利用”background-size:cover;”定。利用方法以下:
- <style>
- .bg {
- position: fixed;
- top: 0;
- left: 0;
- bottom: 0;
- right: 0;
- z-index: -999;
- }
- .bg img {
- min-height: 100%;
- min-width: 1000px;
- width: 100%;
- }
-
- @media screen and (max-width: 1000px) {
- img.bg {
- left: 50%;
- margin-left: -500px;
- }
- }
- </style>
代
操作以後我,器的度小於配景片原始的度,背景片有形的情形生,因我要加上min-width: 1000px;限制配景片小的比例。中1000px是後片的原始度
的,了要定配景中的扭木可以呈在面中,我要再做一些整。背景片程度置中,以後的CSS以下:

- <style>
- .bg {
- position: fixed;
- top: 0;
- left: 0;
- bottom: 0;
- right: 0;
- z-index: -999;
- }
- .bg img {
- min-height: 100%;
- width: 100%;
- }
- </style>
代
css
- <body>
- <div class="bg">
- <img src="background.jpg">
- </div>
- </body>
代 站架 以下文出自: 文章定位: