Andrea Casaccia
Andrea Casaccia

Reputation: 4971

CSS selector to match class with number greater than

I have a mobile hybrid application developed with Sencha Touch 2 which needs some customization based on the iOS version it is running on.

I used to have the following selector in my Sass stylesheet:

.x-ios-7 {
/* put here iOS7 customizations */

}

Now with iOS8 the framework adds a x-ios-8 class instead of x-ios-7 and the customizations are obviously broken.

Is there a way to select all classes with x-ios-{i} where {i} >= 7?

[EDIT]

Sass usage is allowed. I don't want to hardcode known cases.

Upvotes: 2

Views: 2079

Answers (2)

imcg
imcg

Reputation: 2649

In vanilla CSS you could use the attribute selector with a wildcard to match any className that begins with "x-ios-":

[class*='x-ios-'] {
  /* all ios */
}

And then hard-code known cases that need something extra:

.x-ios-7 {
  /* ios 7 */
}

Edit: as doc's answer suggests you can target >= ios7 like this (fiddle):

[class*='x-ios-']:not(.x-ios-3):not(.x-ios-4):not(.x-ios-5):not(.x-ios-6) {
   /* ios >= 7 */
}

Upvotes: 2

davidcondrey
davidcondrey

Reputation: 35983

SASS

@for $i from 3 through 6 {
    .x-ios-#{$i} { background:blue; }
}

generates

.x-ios-3 { background:blue; }
.x-ios-4 { background:blue; }
.x-ios-5 { background:blue; }
.x-ios-6 { background:blue; }

Regular CSS

div { width:100px;height:100px;border:1px solid black;float:left; }
[class^="x-ios-"]:not([class*="1"]):not([class*="2"]) { background:blue; }

<div class="x-ios-1"></div>
<div class="x-ios-2"></div>
<div class="x-ios-3"></div>
<div class="x-ios-4"></div>
<div class="x-ios-5"></div>
<div class="x-ios-6"></div>

enter image description here


Or come up with a nth recipe for whatever your use case is..

:nth-child(n+5) matches children 5, 6, 7, ...
:nth-child(2n+5) matches children 5, 7, 9, ...
:nth-child(-n+7) matches children 1, 2, 3, 4, 5, 6, 7
:nth-child(-3n+8) matches children 2, 5, and 8

Upvotes: 4

Related Questions