好的,所以我遇到了这个让背景图像响应的解决方案:
Responsive css background images
我很抱歉重新发布这个问题,但实际上他们的解决方案都没有对我有用。
HTML:
<div id="fourohfour_home"></div>
CSS:
#fourohfour_home {
background-image:url('image.png');
height:120px;
width:120px;
}
我究竟如何做出这种反应?例如当页面的宽度小于图像的宽度时,它会正确缩放。
答案 0 :(得分: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 :(得分: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 */
}
答案 2 :(得分:0)
为了获得响应,您通常必须使用百分比而不是像素值。因此,如果您将元素的高度和宽度设置为100%,并将其父元素的 所有 设置为您想要的完整高度和宽度(包括html和()),其他问题的代码应该有效。试试http://goo.gl/2GrwyR