Several elements with similar css

I have several html elements. They use very similar css styles. The only difference is the border style (one element has only a left border, the other only on the right, etc.).

So far, I have used several different styles that have only one line of code. This has seriously inflated my css file. Is there a better solution to my problem? Is there any inheritance I could use?

+7
source share
4 answers

There are many ways to achieve this.

  • Use multiple selectors:

    selector #1, selector #2, selector #3 { /* common styles */ } selector #1 { border-left: none; } selector #2 { border-right: none; } selector #3 { border-top: none; } 
  • Depending on the structure of the document, you might try something like this:

     <ul> <li>Element #1</li> <li>Element #2</li> <li>Element #3</li> </ul> ul li { /* common styles */ } ul li:first-child { border-left: none; } ul li:last-child { border-right: none; } 
  • Use several classes:

     <ul> <li class="border no-left">Element #1</li> <li class="border">Element #2</li> <li class="border no-right">Element #3</li> </ul> .border { /* common styles */ } .border.no-left { border-left: none; } .border.no-right { border-right: none; } 
+5
source

You can declare an item with multiple classes.

 <div class="general-class left-border-class"></div> <div class="general-class top-border-class"></div> ... 
+4
source

CSS

 .border { border: solid #555 2px; width: 100px; height: 100px; } .border.left { border-width: 0 2px 0 0; } .border.right { border-width: 0 0 0 2px; } 

HTML

 <div class="border left"></div> <div class="border"></div> <div class="border right"></div> 
+3
source

In this particular scenario - where you have elements with different border styles - you can use the :first-child class pseudo-class.

Live demo: http://jsfiddle.net/7WJe9/1/

0
source

All Articles