13

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>
Radex
  • 7,815
  • 23
  • 54
  • 86
  • Possible duplicate of [Can I change the fill color of an svg path with CSS?](https://stackoverflow.com/questions/9529300/can-i-change-the-fill-color-of-an-svg-path-with-css) – Rob Dec 29 '17 at 14:08
  • The rect elements have no visible fill because 1/2 the stroke width is >= the width so all you see is the stroke and stroke colour. – Robert Longson Dec 29 '17 at 15:11

1 Answers1

7

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>
Temani Afif
  • 245,468
  • 26
  • 309
  • 415