代码之家  ›  专栏  ›  技术社区  ›  Michael Mao

CSS正文背景图像即使在放大/缩小时也固定为全屏

css
  •  25
  • Michael Mao  · 技术社区  · 14 年前

    我正试图通过CSS实现以下目标:

    我想保持身体背景图像固定在全屏上,这是由以下代码完成的:

    body
    {
        background: url(../img/beach.jpg) no-repeat fixed 100% 100%;
    }
    

    有没有更好的方法纯粹用CSS来实现这一点?我没有为背景图像找到一个好的属性。

    或者我应该开始考虑jQuery来动态地操纵宽度和高度吗?它们都被设定为100%,所以我认为这应该“一如既往”起作用:(

    谢谢你的建议!

    6 回复  |  直到 14 年前
        1
  •  25
  •   Pat    14 年前

    我用过 these techniques

    full size background image jQuery plugin 如果你想摆脱上面的错误。

        2
  •  61
  •   Itay Grudev    9 年前

    还有另外一种方法

    使用

    background-size:cover
    

    就是这样 全套css是

    body { 
        background: url('images/body-bg.jpg') no-repeat center center fixed;
        -moz-background-size: cover;
        -webkit-background-size: cover;
        -o-background-size: cover;
        background-size: cover;
    } 
    

    最新的浏览器支持默认属性。

        3
  •  4
  •   WorkingMatt    11 年前

    你可以用纯css做很多事情…css属性 background-size cover 正如兰吉思指出的那样。

    这个 background-size: cover 设置缩放图像以覆盖整个屏幕,但如果屏幕和图像的纵横比不同,则可能意味着部分图像脱离屏幕。

    一个好的选择是 background-size: contain 它调整背景图像的大小以适应较小的宽度和高度,确保整个图像是可见的,但如果纵横比不同,可能会导致字母装箱。

    例如:

    body {
          background: url(/images/bkgd.png) no-repeat rgb(30,30,30) fixed center center;
          background-size: contain;
         }
    

    我发现其他不太有用的选项有: background-size: length <widthpx> <heightpx> 设置背景图像的绝对大小。 background-size: percentage <width> <height> 背景图像是窗口大小的百分比。 (见 w3schools.com's page )

        4
  •  2
  •   dafNou    10 年前

    在css文件中添加以下内容:

    .custom_class
     {
        background-image: url(../img/beach.jpg);
        -moz-background-size: cover;
        -webkit-background-size: cover;
        -o-background-size: cover;
        background-size: cover;
     }
    

    <div class="custom_class">
       ...
    </div>
    
        5
  •  1
  •   T J    9 年前

    你只需应用 width:100%

    position:absolute; width:100%;

        6
  •  1
  •   subindas pm    7 年前

    像这样直接使用

    .bg-div{
         background: url(../img/beach.jpg) no-repeat fixed 100% 100%;
    }
    

    或者单独调用CSS

    .bg-div{
        background-image: url(../img/beach.jpg);
        -moz-background-size: cover;
        -webkit-background-size: cover;
        -o-background-size: cover;
        background-size: cover;
    }