skip to Main Content

I’m trying to get all bold texts from an anchor tags to have the same style.

I tried with :

a > h1,h2,h3,h4,h5,h6,strong,b,d1,d2,d3,d4,d5,d6{
  font-weight:var(--medium);
}

But the style is only applied on <h1>.

So I tried with :

a>h1,a>h2,a>h3...{ }

But then I realized that typing out :hover and :active would be tedious at it’ll take a total of 28 times.

What is the quickest way to type out a > h1,h2,...,d5,d6 including both :hover and :active ?

2

Answers


  1. If you are trying to avoid to repeat the target elements, you’ll have to use JavaScript and not CSS.

    With JavaScript, you can add an EventListener to the DOM content loading, and use a selector there for your {a > h1, a > h2, ...}.

    It should look like this:

    document.addEventListener('DOMContentLoaded', function() {
      const targetElements = document.querySelectorAll('a > h1, a > h2');
    
      targetElements.forEach(function(element) {
        element.style.color = 'red';
      });
    });
    

    And for :hover and :active, you should use the same eventListener and add some EventLister for mouseover, mouseout, mouseup and mousedown.

    The completed JavaScript code should look like this. Of course, rearrange the const targetElements and the change of style you want to do for each actions:

    document.addEventListener('DOMContentLoaded', function() {
      const targetElements = document.querySelectorAll('a > h1, a > h2');
    
      targetElements.forEach(function(element) {
        element.style.color = 'red';
    
        element.addEventListener('mouseover', function() {
          element.style.color = 'blue';
        });
    
        element.addEventListener('mouseout', function() {
          element.style.color = 'red';
        });
    
        element.addEventListener('mousedown', function() {
          element.style.textDecoration = 'underline';
        });
    
        element.addEventListener('mouseup', function() {
            element.style.textDecoration = '';
        });
      });
    });
    

    Check it out here: demo

    Login or Signup to reply.
  2. CSS :is can help here.

    <style>
      a> :is(h1, h2, h3, h4, h5, h6, strong, b, d1, d2, d3, d4, d5, d6) {
        font-weight: var(--medium);
        color: red;
      }
      
      a:hover> :is(h1, h2, h3, h4, h5, h6, strong, b, d1, d2, d3, d4, d5, d6) {
        font-weight: var(--medium);
        color: green;
      }
    </style>
    <a>
      <h2>h2</h2>
    </a>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search