如何在不丢失比例的情况下使背景图像响应

Lui*_*lho 5 html css3 css-transitions

我正在用HTMLCSS3做动画,我需要和背景图像一起调整.问题是内容保持在其中div.我为此设置了height宽度fixed,但是不起作用.当我尝试使用动态比例(%auto)时,background-size: contain;动画不遵循原始路径.

固定大小遵循路径:

在此输入图像描述 和移动也很好

在此输入图像描述

但是,没有响应:

在此输入图像描述

动态大小响应,但不遵循路径:

在此输入图像描述 在此输入图像描述

更改的代码:

 #main{
   position:relative;
-  left: 0;
-  height: 1366px;
-  width: 980px;
+  // left: 0;
+  height: 100%;
+  width: 100%;
   overflow:hidden;
   background: url('../images/bg.png');
   background-repeat: no-repeat;
-
+  background-size: contain;
 }
Run Code Online (Sandbox Code Playgroud)

DEMO

这是我的index.html

  <div id="main">
    <div class="participant" style="z-index: 4;">
  <div class="car">
      <img class="photo" src="https://scontent-atl3-1.xx.fbcdn.net/v/t1.0-1/c21.21.259.259/s50x50/529297_568082979888645_1727470385_n.jpg?oh=c75505b8b23ff9abd26be1fd5771f81d&amp;oe=582BAD0F" alt="">
      <img class="sprite" src="http://i.imgur.com/OwYhg9T.png" alt="">
    </div>
  </div>


  </div>
Run Code Online (Sandbox Code Playgroud)

和我的 animation.css

@charset "utf-8";
/* CSS Document */
body, html {
  height: 100%;
}


body {
  padding:0;
  margin:0;
}

#main{
  position:relative;
  left: 0;
  height: 1366px;
  width: 980px;
  overflow:hidden;
  background: url("http://i.imgur.com/G4gs6EG.png");
  background-repeat: no-repeat;

}



@-moz-keyframes move
{
  from {
    right: -30%;
    top: 8%;
  }

  to {
    right: 140%;
    top: 80%;
  }
}

@-webkit-keyframes move
{
  from {
    right: -30%;
    top: 8%;
  }

  to {
    right: 140%;
    top: 80%;
  }
}

.participant {
  position: absolute;
  display: inline-block;
  height:200px;
  width: 200px;
  right: 140%;
  top: 80%;
  -moz-animation:move 10s  linear infinite;
  -webkit-animation:move 10s  linear  infinite;
}

.sprite{
  width: 100%;
  height: 100%;
}

.photo{
  position: relative;
  top: 128px;
  left: 99px;
  width: 50px;
  height: 50px;
}
Run Code Online (Sandbox Code Playgroud)

Bar*_*arp 5

这有点棘手,需要固定背景图像的宽高比.

1.让一切响应.

首先,如果所有东西都是%-based汽车,它将无法工作px-based(因为如果你调整窗口大小,一切都会变小但是汽车将保持不变),所以对于初学者你将不得不改变你的大小汽车到百分比.

2.修复宽高比.

然后,您需要使用绝对和相对位置以及填充的混合来固定宽高比.

在您的情况下,您的包装器的CSS将类似于:

width: 100%;
padding-bottom: 71.74%; /* 980/1366 = ~ 0.7174 */
Run Code Online (Sandbox Code Playgroud)

(您的背景图片是980x1366px)

DEMO

3.未来证明:在每个屏幕上填充屏幕.

遗憾的是,由于纵横比本身,你不能对你的图像周围的空白做太多,我个人会寻找一个16:9的背景图像,如果你需要,它将完全适合大多数台式机/笔记本电脑屏幕要覆盖各种屏幕,您应该使用不同大小的背景媒体查询.

请记住调整padding-bottom容器和图像本身.

希望能帮助到你!