首页 > 解决方案 > CSS - 设置背景颜色时定位背景图像

问题描述

我这里有一支密码笔—— https://codepen.io/mt-ttmt/pen/yjKPZZ

我可以设置元素的背景颜色并设置背景图像

是否可以设置背景图像的大小和位置而不影响背景颜色。

.content{
  background:  url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' version='1' viewBox='0 0 10 6'%3E%3Cpath d='M1.7.3A1 1 0 1 0 .3 1.7l4 4a1 1 0 0 0 1.4 0l4-4A1 1 0 1 0 8.3.3L5 3.58 1.7.29z' fill='red'/%3E%3C/svg%3E"),linear-gradient(to bottom, white, #999);
  background-repeat: no-repeat;

  /* This effects the background color as well*/

  /*  background-size: 20px;
      background-position: 2px 5px; 
  */

  height: 50px;
  width: 200px;
  border: 1px solid grey;
}

标签: css

解决方案


是的,您只需要指定两个值,每个层用 a 分隔,,因为单个值会影响它们。

.content{
  background-image:  
  url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' version='1' viewBox='0 0 10 6'%3E%3Cpath d='M1.7.3A1 1 0 1 0 .3 1.7l4 4a1 1 0 0 0 1.4 0l4-4A1 1 0 1 0 8.3.3L5 3.58 1.7.29z' fill='red'/%3E%3C/svg%3E"),
  linear-gradient(to bottom, white, #999);
  background-repeat: no-repeat;
   background-size: 
    20px,
    100% 100%;
   background-position: 
    2px 5px,
    0 0; 
  height: 50px;
  width: 200px;
  border: 1px solid grey;
}
<div class="content">
  
</div>

或者直接在背景属性中使用该值,而无需为渐变指定值:

.content{
  background:  
  url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' version='1' viewBox='0 0 10 6'%3E%3Cpath d='M1.7.3A1 1 0 1 0 .3 1.7l4 4a1 1 0 0 0 1.4 0l4-4A1 1 0 1 0 8.3.3L5 3.58 1.7.29z' fill='red'/%3E%3C/svg%3E") 2px 5px/ 20px no-repeat,
  linear-gradient(to bottom, white, #999);
  height: 50px;
  width: 200px;
  border: 1px solid grey;
}
<div class="content">
  
</div>


推荐阅读