如何在所有不同的屏幕尺寸上保持相同的背景图像 ratio/size?

How to keep same bakcground-image ratio/size on all different screen sizes?

如何保持背景图像的比例相同,使其看起来适合所有不同的屏幕尺寸?换句话说,我怎样才能确保背景图像看起来总是完美 "centered"。请注意我还有其他几个带有其他背景图像的屏幕,因此该解决方案应该适用于不同的图像,而不仅仅是下面的房子。

CSS :

#background{
     background-image: url("../images/houses.png");
     background-color: whitesmoke; /* Used if the image is unavailable */
     height: 100%; /* You must set a specified height */
     -webkit-background-size: cover;
     -moz-background-size: cover;
     -o-background-size: cover;
     background-size: cover; /* Resize the background image to cover the entire container */
     text-align: center;
     padding: 2.5%;

}

这是所有屏幕尺寸所需的输出。完美对齐:

然而,当我调整大小并尝试不同的尺寸时,背景会错位并且看起来不太好。看起来图片有点偏右:

由于您的 CSS 告诉页面确保背景在宽度和高度上都覆盖整个屏幕,这将导致屏幕出现一些不符合图像纵横比的不规则现象。它必须拉伸以覆盖第二个屏幕的整个高度,但 "cover" 会在两个方向缩放,因此它会不断增加图像大小,直到覆盖整个屏幕。如果你只想确保背景水平填充屏幕(并且不介意底部可能有 space 留给较高的屏幕),只需设置宽度以填充整个屏幕:

背景大小:100% 自动;

试试这个:

#background{
  background-image: url("../images/houses.png"); /* The image used */
  background-color: whitesmoke; /* Used if the image is unavailable */
  height: 500px; /* You must set a specified height */
  background-position: center; /* Center the image */
  background-repeat: no-repeat; /* Do not repeat the image */
  background-size: cover; /* Resize the background image to cover the entire container*/
}