Home > front end >  How can I combine the same CSS properties for different elements?
How can I combine the same CSS properties for different elements?

Time:10-14

I have two elements: tooltip and tooltip-line. There is common properties for each elements:

[tooltip]::after, [tooltip-line]::after  {
position: absolute;
opacity: 0;
visibility: hidden;
/* Other common properties */
}

Next, I have different properties for each element.

[tooltip-line]::after  { /* One line tooltip */
    content: attr(tooltip-line);
    white-space: nowrap;
}
[tooltip]::after  { /* Multiline tooltip */
    content: attr(tooltip);
    width: 200px;
    white-space: normal;
}

Is this a correct usage? Including similar classes. Or should I copy all properties to each declaration block?

CodePudding user response:

It's absolutely right to divide the css in multiple blocks.

One of the first thing to know while writing code in any language is NOT to repeat yourself.

CodePudding user response:

Here's a different approach which might be slightly more scalable. Using CSS custom variables, we can override any default class values by resetting them in the multiline class. Finally, I would make the attributes containing the tooltip content identical—and valid data attributes—if possible.

.tooltip::after {
  --tooltip-white-space: nowrap;
  
  content: attr(data-tooltip-content);
  white-space: var(--tooltip-white-space);
}

.tooltip.multiline::after {
  --tooltip-white-space: normal;
}

.container {
  width: 250px;
  border: 1px solid red;
}
<div class="container">
  <div class="tooltip" data-tooltip-content="my tooltip content should not wrap no matter what"></div>

  <div class="tooltip multiline" data-tooltip-content="my multliline tooltip content should wrap"></div>
</div>

jsFiddle

  • Related