开发者

CSS reducing syntax

I'd like two different HTML elements that are at the same nesting level to have identical CSS property values. Is there an alternative to this wasteful syntax?

.level1 .level2 .level3 element1 { /*rules*/ }
.le开发者_如何转开发vel1 .level2 .level3 element2 { /*rules*/ }

I was thinking

.level1 .level2 .level3 element1, .level1 .level2 .level3 element2 { /*rules*/ } 

...but this looks confusing and doesn't reduce much.

Is the best method to define a new class?


.level1 .level2 .level3 element1, 
.level1 .level2 .level3 element2 { }

or

.level1 .level2 .level3 * { }

are your only other syntactical alternatives if you don't alter the source code. The latter would fail if you have other elements other than element1 and element2. I'd go with the former.


Well if you're putting classes on them like "level2" then just do:

.level2 { /* rules */ }

meaning there's no need to go:

.level1 .level2 .level3 { /* rules */ }

if you simply assume that level3 is correctly placed, which should simplify such things as:

.level3 div, .level3 span, .level3 p { /* rules */ }

versus the alternative.

There is no way of saying:

.level3 (div or span or p) { /* rules */ }

unfortunately.

but if you want to specify the rules by element depth, it's a little trickier. The easiest way is to use the child selector:

ul li > ul li > ul li { /* rules */ }

if you know the structure and can reasonably express it. The problem with this approach is that IE6 doesn't support the child selector. If you do this:

ul li ul li ul li { /* rules */ }

those rules will apply to the 3rd level and below, not just the third level. That can get tricky to correctly specify in light of rules at different levels that might contradict each other:

ul li { /* rules for 1st, 2nd, 3rd level */ }
ul li ul li { /* rules for 2nd and 3rd level */ }
etc

That might work depending on what you want to do or it might not.


If

.level1 .level2 .level3 element1, .level1 .level2 .level3 element2 { /*rules*/ }

looks confusing, why not split it onto two lines?

.level1 .level2 .level3 element1,
.level1 .level2 .level3 element2 {
    /*rules*/
}


I tend to go for as short a selector as possible. For example:

.level3 elem1,
.level3 elem2 {
    /* rules */
}

Unless you have a .levelX .level3 elem1 then the rule above won't clash with anything else. It's also quicker for the browser to parse because it doesn't have to check as many classes each time.

To be honest, if you have more than a couple of levels of classes then it may be worth checking your HTML structure and seeing if you can get rid of a few divs and the like.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜