开发者

Using Nth - CSS VS Jquery

Is there any reason why someone would choose to use the nth function within a CSS only rather than applying this through jquery where it's more compatible with IE.

Should it just be done within jquery to begin with and never 开发者_Python百科used in a stylesheet?

I hope this makes sense and someone can help.

Cheers


No. Not everybody uses their browser with Javascript enabled. Also, applying styles via Javascript is slower than CSS ruled because it requires a script to run for the style to be applied.

That said, it could be a good idea to use jQuery to provide nth-child compatibility for browsers that don't support it.


The reason why you would use jQuery/javascript now is because not all browsers support the nth css selector.

For instance, with :nth-child... there is no IE8 <= support:

http://reference.sitepoint.com/css/pseudoclass-nthchild

However, I would add it to the css for future use and get rid of the scripting once a certain # of browsers were on board.


You can use :nth-child in only your CSS when you simply don't care about compatibility with older versions of IE.

Many sites simply do not need to work 100% perfectly in older versions of IE, especially when you consider :nth-child is often used for eye candy such as zebra striping which is not vital.

Using plain CSS is faster than doing it through jQuery, although the speed difference is not huge: in browsers that do not support :nth-child, Sizzle must emulate it (slow) and there's no way around doing that. In browsers that do support :nth-child, it goes straight to querySelectorAll which is very fast.

Selectivizr is another choice - it runs in only older versions of IE, and saves you from having to manually write the actual jQuery code ($('..:nth-child(2n)').addClass(..);), so when you're developing, all that has to be written is the CSS version.


CSS is faster for these operations. Put simply, it just gets parsed and added to the elements, but if you use jQuery for this, there is extra JS to be parsed, executed, some loops, function calls... Not that there's any noticeable time difference on small tables, but still.

It is way smaller to do it with CSS as well. If you really need to support IE, you could always check if the browser used is IE (I think jq has support for this?) and then fallback to js. (which eliminates my above point, but it's still better to use css.)


I will probably use both - apply it via CSS rule (the preferred way) and also via jquery (selectively for non-compatible browser). Hopefully, with increasing standard compliance, the script solution will not be required.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜