Is there any way to style a <svg> fill property inside a <p> tag using just one modifier without violating the BEM CSS principles?

94 views Asked by At

I wonder if I could style <svg> fill color with just paragraph--color modifier.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Teste</title>
  </head>
  <body>
    <p class="paragraph paragraph--color">
      <svg fill="red" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg">
        <path
          fill-rule="evenodd"
          d="M10 9a3 3 0 100-6 3 3 0 000 6zm-7 9a7 7 0 1114 0H3z"
          clip-rule="evenodd"
        ></path>
      </svg>
      SVG and text should change color with paragraph--color modifier only.
    </p>
    <style>
      * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
      }

      body {
        display: flex;
        font-family: sans-serif;
        background-color: whitesmoke;
        font-size: 20px;
        height: 100vh;
      }

      .paragraph {
        display: flex;
        align-items: center;
        margin: auto;
      }

      .paragraph--color {
        color: blue;
      }
    </style>
  </body>
</html>

I could style svg fill color using

.paragraph--color svg {
  fill: blue;
}

but I would be violating BEM CSS principles.

Is there any way to do this without violating BEM principles and with no new classes added to just by using pseudo classes and pseudo selectors?

1

There are 1 answers

0
JHeth On

You can just set the SVG's fill as currentColor then set the color on .paragraph--color to what you want the fill to be. This works with stroke-color for SVG as well.

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  display: flex;
  font-family: sans-serif;
  background-color: whitesmoke;
  font-size: 20px;
  height: 100vh;
}

.paragraph {
  display: flex;
  align-items: center;
  margin: auto;
}

.paragraph--color {
  color: blue;
}
<p class="paragraph paragraph--color">
  <svg fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg">
        <path
          fill-rule="evenodd"
          d="M10 9a3 3 0 100-6 3 3 0 000 6zm-7 9a7 7 0 1114 0H3z"
          clip-rule="evenodd"
        ></path>
      </svg> SVG and text should change color with paragraph--color modifier only.
</p>