Home > Blockchain >  which css selector to use to avoid code repetition
which css selector to use to avoid code repetition

Time:10-15

#MainPage-OpenMenu:hover path:nth-child(1) {
  fill: #49ffad;
  transition: 1s;
}

#MainPage-OpenMenu:hover path:nth-child(2) {
  fill: #49ffad;
  transition: 1s;
}

As you can see my code is repeated. How can I make it shorter to avoid duplicate code ?

CodePudding user response:

You can use :is():

#MainPage-OpenMenu:hover path:is(:nth-child(1), :nth-child(2)) {
  fill: #49ffad;
  transition: 1s;
}

https://www.w3.org/TR/selectors-4/#matches

CodePudding user response:

Use a comma in between selectors to apply the same css to multiple selectors. For example,

#MainPage-OpenMenu:hover path:nth-child(1), #MainPage-OpenMenu:hover path:nth-child(2) {
  fill: #49ffad;
  transition: 1s;
}

See snippet for a similar example.

div {
  width: 100px;
  height: 100px;
  border: 1px solid black;
  margin: 10px;
}

#div1, #div2 {
  background-color: red;
}
<div id="div1"></div>
<div id="div2"></div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

You can add more with " , " check this page for more info. https://www.w3schools.com/css/css_selectors.asp

#MainPage-OpenMenu:hover path:nth-child(1), 
#MainPage-OpenMenu:hover path:nth-child(2) {
 fill: #49ffad;
 transition: 1s;
}

CodePudding user response:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Static Template</title>
    <style>
      .tempdiv:hover > div > :nth-child(1) {
        color: red;
      }
      .maindiv:hover > div > :nth-child(1),
      .maindiv:hover > div > :nth-child(2) {
        color: red;
      }
    </style>
  </head>
  <body>
    <div class="tempdiv">
      <h3>However on div and change color of first child</h3>
      <div>
        <h1>Mango</h1>
        <h1>Orange!</h1>
      </div>
    </div>

    <div class="maindiv">
      <h3>However on div and change color of first and second child</h3>
      <div>
        <h1>Mango</h1>
        <h1>Orange!</h1>
      </div>
    </div>
  </body>
</html>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Simple and straight forward example to clear everything you are looking for. I hope this will answer the question

  •  Tags:  
  • css
  • Related