Francisco Romero
Francisco Romero

Reputation: 13199

How to avoid repeat the same lines on CSS?

I do not want to repeat the same property all the time on my CSS.

In my case, I have three media queries in which I change the property of padding of a specific element and after I need to put it as the beginning:

@media (max-width: 1000px){
     ul > a{
         padding-top: 20px;
         padding-bottom: 20px;
     }
}

@media (max-width: 750px){
     ul > a{
         padding-top: 16px;
         padding-bottom: 16px;
     }
}

@media (max-width: 500px){
     ul > a{
         padding-top: 20px;
         padding-bottom: 20px;
     }
}

As you can see, I have to put the same code on the first and on the third one media query and I would like to reduce the amount of lines of my CSS.

I would like to wrap these lines into a variable or something similar:

ul > a{
    padding-top: 20px;
    padding-bottom: 20px;
}

and use them in the whole CSS each time I need it.

I found that there is an experimental technology to create variables on CSS but that it has not been stabilized yet and it does not have a full browser support.

Thus, is there a method to use more than one line on CSS without repeating them?

Thanks in advance!

Upvotes: 0

Views: 944

Answers (2)

Shaggy
Shaggy

Reputation: 6796

Just define the common rule without a media query and then use media queries to override it as necessary, like so:

ul a{
    padding:20px 0;
}
@media (max-width:750px){
    ul a{
        padding:16px 0;
    }
}

Alternatively, add min-width to your media queries and create a new one to define all the common rules in, like so:

@media (max-width:500px),(min-width:751px) and (max-width:1000px){
    ul a{
        padding:20px 0;
    }
}
@media (min-width:501px) and (max-width:750px){
    ul a{
        padding:16px 0;
    }
}

Upvotes: 2

Nenad Vracar
Nenad Vracar

Reputation: 122057

You could use one query with min and max width Fiddle, also only li element can be direct child of ul element (i used color instead of margin form demo)

ul a {
  color: blue;
}
@media screen and (min-width: 500px) and (max-width: 750px) {
  ul a {
    color: red;
  }
}
<ul>
  <li><a href="">Lorem</a></li>
  <li><a href="">Lorem</a></li>
</ul>

Upvotes: 0

Related Questions