css 实现background背景颜色随着屏幕的宽度变化而变化,主要使用到css媒体@media, 通过@media为不同宽度的屏幕设置不同的背景颜色,从而实现了background背景颜色随着屏幕的宽度变化而变化,具体源代码如下所示:

<!DOCTYPE html>
<html>
<head>
<  name=\"viewport\" content=\"width=device-width\" />
<style type=\'text/css\'>
body {
  background: black;
}

@media(max-width:1024px) {
  body {
    background: red;
  }
}
@media(max-width:768px) {
  body {
    background: blue;
  }
}
</style>
</head>
<body>
</body>
</html>

在1024px以上的屏幕上显示的是黑色背景(background: black;),在768px到1024px之间的屏幕上显示的是红色背景(background: red;),768px以下的屏幕上显示蓝色背景(background: blue;)

注意这里一定要加上< name="viewport" content="width=device-width" />

大家可以把本文章的源代码粘贴到自己的电脑上运行以下。

收藏 打印