我正在尝试在CSS中设置一个后退选项,以在使用移动浏览器时将背景图片更改为彩色。
是否有一种方法可以设置回退,当像素达到最大宽度时,该回退将起作用。
如我下面的代码片段所示,“仅在没有顶部主体类的情况下,“纯媒体屏幕和(最大宽度:600像素)有效。”
body {
margin: 0;
background-image: url(https://api.timeforkids.com/wp-content/uploads/2019/09/final-cover-forest.jpg);
background-size: auto;
position: absolute;
top: 50%;
left: 50%;
margin-right: -50%;
transform: translate(-50%, -50%)
}
@media only screen and (max-width: 600px) {
body {
background-color: lightblue;
}
}
input{
background-color: #03fcd3;
border: none;
color: white;
padding: 16px 32px;
text-decoration: none;
margin: 4px 2px;
cursor: pointer;
}
答案 0 :(得分:3)
您没有覆盖background-image
规则,这就是为什么图像仍在显示的原因。您设置了背景颜色,但是背景图像仍然会显示。
此外,您应该在媒体查询中为较大的屏幕添加图像,而不是在较小的屏幕中将其删除-否则它仍然会加载。始终首选移动优先:)
尝试以下操作(如果您将浏览器窗口缩小,则会看到蓝色背景):
body {
background-color: lightblue;
/* the rest of the CSS that applies on all screen sizes, e.g.: */
margin: 0;
background-size: auto;
position: absolute;
top: 50%;
left: 50%;
margin-right: -50%;
transform: translate(-50%, -50%)
}
/* Note: we show min 601px because it was max: 600px*/
@media only screen and (min-width: 601px) {
body {
background-image: url(https://api.timeforkids.com/wp-content/uploads/2019/09/final-cover-forest.jpg);
/* Add any other CSS for 600+ screens here */
}
}
请注意,新的媒体查询设置为601px -您正在使用max:600px(用于小屏幕),因此CSS(用于小屏幕)最多适用于(包括)600px。
混合使用max-width:600px
和min-width:600px
可能会导致意外行为,因为两者媒体查询都将应用600px。
答案 1 :(得分:1)
尝试设置两个媒体查询,并且一开始不要设置背景。
未设置初始身体背景
对于移动设备:
@media only screen and (max-width: 600px) {
body {
background-color: lightblue;
}
}
对于计算机:
@media only screen and (min-width: 600px) {
body {
background-image: url (https://api.timeforkids.com/wp/content/uploads/2019/09/final-cover-forest.jpg);
background-size: auto;
}
}