如何使CSS背景图像响应? [重复]

问题描述 投票:2回答:3

这个问题在这里已有答案:

好的,所以我遇到了这个让背景图像响应的解决方案: Responsive css background images

我很抱歉重新发布这个问题,但实际上他们的解决方案都没有对我有用。

HTML:

<div id="fourohfour_home"></div>

CSS:

#fourohfour_home {
    background-image:url('image.png');
    height:120px;
    width:120px;
}

我究竟如何做出这种响应?例如当页面的宽度小于图像的宽度时,它会正确缩放。

html css css3 responsive-design background-image
3个回答
11
投票

你只需要定义#fourohfour_home的宽度和高度,以便背景图像知道在哪个容器中是contained。就像是:

#fourohfour_home{
    background-image:url('https://www.example.com/img/404_home.png');
    background-repeat:no-repeat;
    background-size:contain;
    background-position:center;
    height: 120px;
    width: 20%;
}

1
投票

你应该use media queries as always,然后设置背景的尺寸:

@media all and (max-width: 639px) and (min-width: 320px) {
    #fourohfour_home {
        background-size: 320px 240px;
    }
}

在这个例子中,我改变了你给出的图像的大小,对于宽度小于640的情况。如果它更大,我使用另一个分辨率:

@media all and (max-width: 799px) and (min-width: 640px) {
    #fourohfour_home {
        background-size: 640px 480px;
    }
}

如果我想要一个分辨率更高的图像,我甚至可以改变图像:

@media all and (max-width: 799px) and (min-width: 640px) {
    #fourohfour_home {
        background-image: url('my-image-640.png');
        background-size: 640px 480px;
    }
}

编辑它属于相同的CSS定义:

/* for default - too short - size */
@media all and (max-width: 319px) {
    #fourohfour_home {
        background-image: url('my-image-very-small.png'); /*in the case you have another image for this resolution - usually you'll never have these sizes as for today*/
        background-size: 200px 150px;
    }
}

@media all and (max-width: 639px) and (min-width: 320px) {
    #fourohfour_home {
        background-image: url('my-image-320.png'); /*in the case you have another image for this resolution*/
        background-size: 320px 240px;
    }
}

@media all and (max-width: 799px) and (min-width: 640px) {
    #fourohfour_home {
        background-image: url('my-image-640.png'); /*in the case you have another image for this resolution*/
        background-size: 640px 480px;
    }
}

@media all and (max-width: 1023px) and (min-width: 800px) {
    #fourohfour_home {
        background-image: url('my-image-800.png'); /*in the case you have another image for this resolution*/
        background-size: 800px 600px;
    }
}

/* this one goes for default images - bigger sizes */
@media all and (min-width: 1024px) {
    #fourohfour_home {
        background-image: url('my-image-1024.png'); /*in the case you have another image for this resolution*/
        background-size: 1024px 768px;
    }
}

/* this will have no @media, so will apply for every resolution */

#fourohfour_home {
    background-repeat:no-repeat;
    background-position:center;
    width: 100%; /* assuming you want to expand your div in a screen-dependent way */
}

0
投票

为了获得响应,您通常必须使用百分比而不是像素值。因此,如果您将元素的高度和宽度设置为100%并将其所有父元素设置为您想要的全部高度和宽度(包括html和body),则其他问题的代码应该有效。试试http://goo.gl/2GrwyR

© www.soinside.com 2019 - 2024. All rights reserved.