1

I want to select all a tag in here but don't want to repeat the same line like " #s1 span a " all the parent elements have different ids but inner elements are the same or have a same class. I'm unable to figure out a way to do it in a short way. it's just a sample of my problem I have a bigger project where I need to use same css properties on many blockes elements. I mean wrapper blocks ids are different but child elements classes are same.

<style>
#sl,#s2,#s3 span.me a {
  background-color: yellow;
}
</style>

<h1 id="sl">
    <span class="me"> 
            <a href="">Welcome to My Homepage<a>
    <span>
    </h1>
<h1 id="s2">
       <span class="me">
          <a href="">Welcome to My Homepage<a>
       <span>
 </h1>
 <h1 id="s3"> 
    <span class="me">
         <a href="">Welcome to My Homepage<a>
    </span>
      </h1>
Manish Kumar
  • 79
  • 1
  • 12

1 Answers1

1

In CSS, OR clauses represented by , have the lowest precedence, and you cannot change that with parentheses like in other languages. You can see each comma-separated section as a pipeline, which begins with a set of all elements of the page and progressively gets reduced. There's no way to avoid repetition in your case:

#sl span.me a,
#s2 span.me a,
#s3 span.me a { ... } 

However, this is a bad idea because:

  • It's way too specific. If you change the structure of the HTML only a little, you will break the CSS and have to rewrite it. And this would be tedious if you had 1000 sections.
  • It's a pain to wrap your head around the intention of that block. This block of CSS is a style that applies to links within a me-span of the s1, s2 and s3 sections. And why do we need that again?
  • Say you had another style which applied to links within the first paragraph of a blog post and your wrote it #main .blog-post p:first-of-type a, it would override your previous style because it has a higher specificity, which is definitely not obvious at first.

A good practice is to only use single-class selectors when you can, and each class for a single context-independent purpose. For example, when you see .highlighted-link, it's obvious what this class does both in the CSS and the HTML. And you can put one anywhere!

Domino
  • 6,314
  • 1
  • 32
  • 58