Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set fill color for svg rect

Tags:

html

css

svg

I have the following icon in svg, which contain a rect. I need to color in red (now they are in white). With my current CSS solution I am not able to get the result wanted. Any idea how to fix it?

Notes this question is different from other because it related to rect only and not path.

.icon rect {
  fill: red;
}

html {
  background-color: gray;
}
<div class="icon">
  <svg width="50%" height="50%" viewBox="0 0 16 20" version="1.1" xmlns="http://www.w3.org/2000/svg">
    <g stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
      <g transform="translate(-28.000000, -26.000000)" stroke-width="2" stroke="#FFFFFF">
        <rect x="43" y="27" width="1" height="18"></rect>
        <rect x="29" y="27" width="1" height="18"></rect>
      </g>
    </g>
  </svg>
</div>
like image 658
Radex Avatar asked Dec 29 '17 14:12

Radex


People also ask

Can we give color to SVG?

You're largely limited to a single color with icon fonts in a way that SVG isn't, but still, it is appealingly easy to change that single color with color . Using inline SVG allows you to set the fill , which cascades to all the elements within the SVG, or you can fill each element separately if needed.

What is fill rule in SVG?

The fill-rule attribute is a presentation attribute defining the algorithm to use to determine the inside part of a shape. Note: As a presentation attribute, fill-rule can be used as a CSS property. You can use this attribute with the following SVG elements: <altGlyph> <path>


1 Answers

You need to change stroke value of g (a value that you also specified inline) because it's going above the rect:

.icon g {
  stroke: rgba(0,0,0,0.5);
}
.icon rect {
  fill: red;
}

html {
  background-color: gray;
}
<div class="icon">
  <svg width="50%" height="50%" viewBox="0 0 16 20" version="1.1" xmlns="http://www.w3.org/2000/svg">
    <g stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
      <g transform="translate(-28.000000, -26.000000)" stroke-width="2" stroke="#FFFFFF">
        <rect x="43" y="27" width="1" height="18"></rect>
        <rect x="29" y="27" width="1" height="18"></rect>
      </g>
    </g>
  </svg>
</div>

Or simply remove stroke from g :

.icon rect {
  fill: red;
}

html {
  background-color: gray;
}
<div class="icon">
  <svg width="50%" height="50%" viewBox="0 0 16 20" version="1.1" xmlns="http://www.w3.org/2000/svg">
    <g stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
      <g transform="translate(-28.000000, -26.000000)" >
        <rect x="43" y="27" width="1" height="18"></rect>
        <rect x="29" y="27" width="1" height="18"></rect>
      </g>
    </g>
  </svg>
</div>
like image 102
Temani Afif Avatar answered Oct 25 '22 20:10

Temani Afif