为什么backgroundSize无效?

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>test</title>
  <style>
    *{margin:0; padding:0; box-sizing: border-box}
    .test{
      width: 256px;
      height:256px;
      background-image: linear-gradient(to right, transparent 95%, #0ff 95% 100%),
        linear-gradient(to bottom, transparent 95%, #ccc 0);
      
      background-size: 8px 8px;
    }
  </style>
</head>
<body>
  <div class="test"></div>
</body>
</html>

代码如上所示,background-size设置成8px,界面看不到任何效果,使用的是最新的chrome浏览器,请问是什么原因?

阅读 1.1k
avatarAI BotBETA

background-size 属性用于设置背景图像的大小。但是,在你的代码中,background-size 设置为 8px 8px 对你的元素并没有产生可见的效果,因为背景图像实际上并没有应用到你的 .test 元素上。

在你的 CSS 代码中,你使用了两个 linear-gradient 函数来创建背景图像,但是你没有指定 background-image 属性应该应用到哪个元素上。在 CSS 中,如果你希望在一个元素上应用多个背景图像,你需要使用逗号分隔每个 background-image 声明,并且每个背景图像都可以有自己的 background-sizebackground-positionbackground-repeat 等属性。

在你的情况下,你应该将两个 linear-gradient 函数放在同一个 background-image 属性中,并且为每个渐变指定一个 background-size。例如:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>test</title>
  <style>
    *{margin:0; padding:0; box-sizing: border-box}
    .test{
      width: 256px;
      height:256px;
      background-image: 
        linear-gradient(to right, transparent 95%, #0ff 95% 100%),
        linear-gradient(to bottom, transparent 95%, #ccc 0);
      
      background-size: 
        8px 100%, 
        100% 8px;
      
      background-repeat: no-repeat;
    }
  </style>
</head>
<body>
  <div class="test"></div>
</body>
</html>

在这个例子中,我分别为两个渐变设置了 background-size。第一个渐变的 background-size8px 100%,这意味着它的宽度是 8px,高度是元素的整个高度。第二个渐变的 background-size100% 8px,这意味着它的宽度是元素的整个宽度,高度是 8px。我还添加了 background-repeat: no-repeat; 以确保背景图像不会重复。

这样,你应该可以看到两个渐变分别沿着元素的右边和底部延伸,每个渐变的大小都是 8px。

1 个回答

应该是设置的太小了(8px的5%应该是被认为0了,所以没有显示),设置成10px就可以看到了。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题