【问题标题】:set background color, but not to the whole background设置背景颜色,但不是整个背景
【发布时间】:2017-07-07 02:29:16
【问题描述】:

是否可以将背景颜色设置为元素(在我的情况下为 svg),但背景的大小小于实际元素?

假设您有一个宽度为 300 像素、高度为 300 像素的 div。 我想将背景颜色设置为 200px x 200px 的区域。

<object class="tapes"  width="40%" type="image/svg+xml" data="element.svg">

我为什么要问?因为我的元素包含透明度

【问题讨论】:

  • 您可以在 svg 中创建一个矩形并将其作为最低层元素。
  • 酷我在我的 svg 代码中添加了一个新的矩形。不幸的是,我无法通过 css 访问它并设置它的背景颜色。
  • 只需使用 inline 属性即可。 '填充'?

标签: javascript html css svg


【解决方案1】:

我不确定这是否适用于 SVG 对象,但它适用于 HTML 和 CSS。您可以做的是将box-sizing 属性设置为border-box,然后给元素一个border,其颜色与父元素的background-color 相同。在下面的示例中,我将父母的 background-color 和孩子的 border-color 设置为不同的值,以便您了解实际发生的情况。

body {
  width: 100%;
  height: 185px;
  overflow-x: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #ccc;
}

div {
  width: 150px;
  height: 150px;
  box-sizing: border-box;
  border: solid 25px #afafaf;
  background: orange;
}
&lt;div&gt;&lt;/div&gt;

【讨论】:

    【解决方案2】:

    您是否尝试创建一个带有图像的 div 并用纯色覆盖其中的一部分?

    HTML:

    <div>
    <img alt="myImage" src="https://sarasoueidan.com/images/svg-vs-gif--circle-on-transparent-background.svg" />
    </div>
    

    CSS:

    div {
      width: 400px;
      height: 400px;
      border-style: solid;
      border-width: 5px;
    }
    
    div:before{
        position:absolute;
        z-index:-1;
        top:7%;
        left:2%;
        width:45%;
        height:50%;
        content:"";
        background-color:red;
    }
    

    可能不是最好的方法,但是哦,好吧,希望这对你有帮助!

    【讨论】:

      【解决方案3】:

      您可以添加普通背景,然后在该背景上创建您喜欢的任何颜色的阴影。这仍会像常规背景一样显示在内容后面。

      div {
        height: 300px;
        width: 300px;
        background: red;
        -webkit-box-shadow: inset 0 0 0px 50px white;
        box-shadow: inset 0 0 0px 50px white;
        border: 1px solid black;
      }
      <div>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam accumsan tellus tellus, vel iaculis ante bibendum quis. Nam molestie dictum libero, venenatis consectetur diam fermentum eget. Cras nulla mauris, vehicula sit amet dui id, hendrerit laoreet
        augue. Suspendisse id tellus nec felis suscipit vehicula. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Proin posuere sem vitae turpis porta, quis sagittis tortor </div>

      【讨论】:

        猜你喜欢
        • 2023-03-25
        • 1970-01-01
        • 2011-02-11
        • 2012-12-26
        • 1970-01-01
        • 2010-09-17
        • 2018-07-15
        • 2014-09-04
        • 2010-11-10
        相关资源
        最近更新 更多