Tsuneo
Tsuneo

Reputation: 43

Assign different CSS on different childs with class

I have these structures in different pages:

<!-- case one -->
<ul class="lang-inline">
    <li class="lang-active" dir="ltr">...</li>
    <li class="" dir="ltr">...</li> 
    ...
</ul>

<!-- case two -->
<ul class="lang-inline">
    <li class="" dir="ltr">...</li>
    <li class="lang-active" dir="ltr">...</li>
    ...
</ul>    

In each page, there is one .lang-active class li in each ul. What I want to do is to assign different styles on each case.

Since it is a template, I should write the style in one css file.

Are there any way in CSS to do this?

Upvotes: 1

Views: 129

Answers (3)

user3632735
user3632735

Reputation: 1

I think he meant to change the style per page.

In that case you need to recognise the page using some "marker", either an ancestor's id or a dynamic class/id added on the element itself.

The css than will be like

ul.lang-inline > .lang-active {
  background: red;
}

#page2 ul.lang-inline > .lang-active {
  background: blue;
}

Here the example http://jsfiddle.net/egpksme0/1/

Upvotes: 0

dashtinejad
dashtinejad

Reputation: 6253

You can use + selector which is CSS2:

.just-for-markup + .lang-inline .lang-active {
  background: red;
}

.just-for-markup + .lang-inline  + .lang-inline .lang-active {
  background: blue;
}
<div class="just-for-markup"></div>

<!-- case one -->
<ul class="lang-inline">
    <li class="lang-active" dir="ltr">...</li>
    <li class="" dir="ltr">...</li> 
</ul>

<!-- case two -->
<ul class="lang-inline">
    <li class="" dir="ltr">...</li>
    <li class="lang-active" dir="ltr">...</li>
</ul>    

Upvotes: 0

Fahad Hasan
Fahad Hasan

Reputation: 10506

Yes, you can use the nth-child psuedo-selector like this:

.lang-inline:first-child .lang-active {
     //add your styles here for the first-case
}

.lang-inline:nth-child(2) .lang-active {
     //add your styles here for the second-case
}

.lang-inline:first-child .lang-active {
  color: blue;
}

.lang-inline:nth-child(2) .lang-active {
  color: red;
}
<!-- case one -->
<ul class="lang-inline">
    <li class="lang-active" dir="ltr">One</li>
    <li class="" dir="ltr">Two</li> 
    ...
</ul>

<!-- case two -->
<ul class="lang-inline">
    <li class="" dir="ltr">Three</li>
    <li class="lang-active" dir="ltr">Four</li>
    ...
</ul> 

Upvotes: 4

Related Questions