Group css selectors to reuse code

Asked

Viewed 421 times

6

Given my and html and css respectively:

<!DOCTYPE html>
<html>
 <meta charset="UTF-8"> 
<head>
<link rel="stylesheet" type="text/css" href="css/estilos.css">
    <title>Teste</title>
</head>
<body>
<!--<font color="red"><b><i>FIRE</i></b></font>-->
<div class="tipoPokemon">
Tipo <span id="fire">Fire</span><br>
Tipo <span id="water">Water</span><br>
</div>
</body>
</html>

CSS:

.tipoPokemon #fire{
    color: red;
    text-transform: uppercase;
    font-weight: bold;
    font-style: italic;
}

.tipoPokemon #water{
    color: blue;
    text-transform: uppercase;
    font-weight: bold;
    font-style: italic;
}

The idea is the following: Format specific words in the text, note that it only changes if the color in the example. My question is: Can you group the 3 repeating attributes and make a color-only switch ? Ex: Declare the 3 attributes as global and vary only colors.

2 answers

7


use class for this.:

.tipoPokemon span {
    text-transform: uppercase;
    font-weight: bold;
    font-style: italic;
}

.tipoPokemon span#fire{
    color: red;
}

.tipoPokemon span#water{
    color: blue;
}

if you prefer, you can use SCSS:

$vermelho: #F44336;
$azul: #2196F3;

%tipoPokemon {
  text-transform: uppercase;
  font-weight: bold;
  font-style: italic;
}

.tipoPokemon #fire{
    @extend %tipoPokemon;
    color: $vermelho;
}

.tipoPokemon #water{
    @extend %tipoPokemon;
    color: $azul;
}

In the example above, I am using the red and blue adopted by Material Design, and the result will be the following:

.tipoPokemon #fire,
.tipoPokemon #water {
  text-transform: uppercase;
  font-weight: bold;
  font-style: italic;
}

.tipoPokemon #fire{
  color: #F44336;
}

.tipoPokemon #water{
  color: #2196F3;
}
  • It worked, just a doubt: because the span is close to the # and there is no space ?

  • 1

    @Separate Douglas means that one element is inside another, so the element #fire would need to be a descendant of span, while together, it means that it is the same element, so the span need to have id=fire

  • Show, thank you very much.

  • @Douglas also made an example with SASS, you may come to like.

  • God, I liked the idea, I didn’t know the SASS, I’ll study it and thank you.

6

An alternative is to use the :not():

.tipoPokemon span {
  color: red;
  text-transform: uppercase;
  font-weight: bold;
  font-style: italic;
}

.tipoPokemon span:not(#fire) {
  color: blue
}
<div class="tipoPokemon">
  Tipo <span id="fire">Fire</span><br>
  Tipo <span id="water">Water</span><br>
</div>

  • Thank you works too.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.