如何保持背景图像的比例相同,以使其看起来适合所有不同的屏幕尺寸?换句话说,我如何确保背景图像始终看起来完全“居中”。请注意,我还有其他带有其他背景图像的屏幕,因此该解决方案应该适用于不同的图像,而不仅仅是下面的房屋。
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%;
}
这是所有屏幕尺寸的期望输出。完美对齐: https://jsfiddle.net/hsvyc1a8/
但是,当我调整大小并尝试不同的大小时,背景放错了位置,看起来也不是很好。看起来图像有点向右:
答案 0 :(得分:1)
尝试:
#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*/
}
答案 1 :(得分:0)
由于CSS告诉页面确保背景在宽度和高度上都覆盖整个屏幕,因此这将导致屏幕出现一些与图像的纵横比不匹配的不规则现象。它必须拉伸以覆盖第二个屏幕的整个高度,但是“覆盖”在两个方向上都可以缩放,因此它会不断增加图像大小,直到覆盖整个屏幕。如果您只想确保背景水平地填满整个屏幕(并且不介意在底部可以留出更多空间放置较高的屏幕),只需设置宽度即可填满整个屏幕:
背景大小:100%自动;