I used to write OpenGL2.1 apps on C++. Now i am working in HTML5, because i have strong belief it going to be single UI platform.
I know that a lot of CSS3 animations/rules can be forced to GPU. But, none of them allow "user-level" computations.
I know that its not what CSS was designed for, but how can i make animation with simple math on pure CSS? I don't like idea of CPU wakeups.
As an example, simple task, easily solved by shaders with 0 CPU actions:
Timer on pure CSS
.
But it has an issue: it never stops. So, am I able to apply simple conditions? Like stop when animation-stop: 'content' < attr(target)
Mainly for education purposes.
A few ideas:
animation-iteration-count (MDN) is the simplest condition I could think of.
You could also use CSS Custom Properties (aka "CSS Variables") with a bit of JS:
:root {
--count: 19;
}
.selector {
animation-iteration-count: var(--count);
}
Now in JS you just have to modify a single value and that new value is instantly used in many declarations.
With JS, you can toggle class on HTML elements and CSS rules will or won't match depending on their selector rules.
Demos:
Update CSS Variables with JS
Parallax 3D Button with JS controlled CSS variables
You could also see "Conditions" for CSS Variables and CSS locks
But if you want to make something happen or stop, outside of hacks/trick kind of abusing CSS or with overcomplicated code, then JavaScript and DOM Events are the way to go.
You're speaking of GPU, computation, OpenGL so just in case: if you need computation intensive JS then give a try to ServiceWorkers. They can't modify the DOM but they'll run in the background crunching some numbers.
Related
I have started using BEM methodology while writing my CSS and there have been few occasions where I have struggled to find out the best way to do a particular thing.
I would like to take up a simple example of a panel here.
Lets say I am writing a panel component CSS using BEM style. So my CSS might look as follows:
.panel {}
.panel__titlebar {}
.panel__content { display: none; }
A panel can be either chromeless or with chrome. So I define another modifier class for the panel:
.panel--with-chrome {
border: 4px solid black;
border-radius: 4px;
}
Now lets say, the panel can be in a fullscreen/maximized state also in which the chrome and titlebar disappear. Instead of defining modifiers for both panel and titlebar, it would be be wise to define the modifier just on parent (say panel--fullscreen) and rest elements shall change accordingly. So now my CSS becomes:
.panel--fullscreen {
/* something has to be done here */
}
.panel--fullscreen .panel__titlebar { display: none; }
To remove the chrome in fullscreen mode, I can either:
toggle the panel--with-chrome class in JS along with the panel--fullscreen class
overwrite the chrome CSS inside the panel--fullscreen class.
First isn't good because ideally I would like to simply toggle just one class (.panel--fullscreen) in JS to toggle fullscreen mode.
And second one is bad because I'll have to overwrite previous CSS which is a bad practice.
So whats the best way to go about it? Appreciate your comments.
Thanks
The answer depends on many things.
First, how much logic and appearance have "panel--with-chrome" and "panel--fullscreen" modifiers. And also on what kind this logic is.
If "panel--with-chrome" brings a lot of CSS properties and special JS functionality, I would toggle it in JavaScript when applying "panel--fullscreen".
It also depends on a JavaScript framework you use. In "i-bem.js" which we use at Yandex it's easy to react to appending a modifier:
A square changes size modifier when after a click
Reacting on applying a modifier
But if the framework you use doesn't allow to express such a reaction handy, this answer won't work that great for you.
In the other case, when "panel--with-chrome" has not very much properties and doesn't bring any JavaScript logic to a page, I would redefine those CSS properties in "panel--fullscreen" class.
To sum up, there is no universal solution and strict rules to follow. You should decide yourself what will be useful in your case. The decision should depend on many things:
if you expect your project to be maintained in the future, which solution will be easier to support?
capabilities of the JavaScript framework you use
performance stuff
Not in this particular case, but sometimes we measure speed of rendering for variants we are choosing from.
opinion of the other guys, if you work in team
file structure of your project
We, here at Yandex, store CSS and JavaScript for a block in the same block folder. So, it is not a problem to share logic between CSS and JavaScript since they all are in one place.
But if you keep your JavaScript files separately, this can influence on how comfortable it is to support shared logic.
And so on...
I’d go with the first option; you are toggling state after all, so you need to add/remove/toggle classes accordingly. It’s better than undoing a load of stuff in CSS IMO.
Alright, so I recently found this script called "Selectivizr" and I was really excited, but I plugged it into my project, set it up just as it said, and it didn't work.
So, what I am looking for is any sort of JavaScript library/script that will allow me to use CSS3 selectors (especially :checked) in IE8.
Selectivizr seems broken, and hasn't been updated in over a year. Has anybody else had luck with it?
Does anybody know of any other scripts that will allow for use of CSS3 selectors in IE8?
Not looking for CSS3 stylings like border radius, shadows, etc. Just looking for the selectors, like :before, :after, :checked, etc...
Dean Edward's IE9.js is pretty solid, though I have heard of some incompatibility problems when using other libraries as well. Never experienced them myself, but haven't used the library too often in the wild for a long time. Plug it and play, and if it doesn't break then you're all set.
Link: http://code.google.com/p/ie7-js/
Demos: http://ie7-js.googlecode.com/svn/test/index.html
With jQuery code, you can use these few lines to toggle a class on all your checkboxes (or on it's container) any time it's checked or unchecked. This then lets you use regular CSS code in all browsers.
$("input[type='checkbox']").click(function() {
$(this).parent().toggleClass("checked", this.checked);
});
Working example here: http://jsfiddle.net/jfriend00/7jA5r/.
If you dynamically create checkboxes, then you could use the dynamic form of .on() to make sure to catch them.
I would personally rather use a solution with a few lines of code like this than use a heavy library that tries to add CSS style file capabilities. If you were going to use that, make sure you understand what's really going on under the covers before you adopt it.
If you just wanted a selector libraryby itself, the Sizzle selector library works across a wide variety of browsers including all the way back to IE6. It will adapt to the capabilities of the host browser, using as many built-in capabilities as are present and using it's own code when the host browser does not support an explicit capability.
You can use just the selector library itself from here or it is also the selector library inside of jQuery.
It's extremely simple to use. You just do something like this:
var items = Sizzle(":checked");
and you will have an array of DOM elements that match the selector.
This is a long shot, but is there a tool available that optimizes CSS selectors by removing unneeded specificity?
I find that when I write CSS, I deliberately make my selectors more specific than necessary to avoid conflicts and for quasi-documentation.
It would be great if there were a tool that could analyze a given group of rules, determine their "uniqueness" in terms of overlap with other rules, and then strip away any unnecessary specificity.
I can't even begin to imagine how a tool developer would approach all of the scenarios this would require, but I've been blown away by others' ingenuities in this area before and figured it was worth asking.
Update:
I've added a bounty to this question, and the more I think about it, the more I realize how valuable a CSS Specificity Filter would be.
For example, when working with Nested Rules/Selectors in Sass and LESS, excessive nesting is a common and well-known antipattern that can easily lead to overly specific selectors.
There's a good illustration of this in the excellent TutsPlus course Maintainable CSS with Sass and Compass:
body {
div.container {
p {
a {
color: purple;
}
}
}
}
Sass will follow these nesting instructions and produce the following CSS output, raising no objection to any unneeded specificity:
body div.container p a {
color: purple;
}
If a Specificity Filter did/does exist, however, it would create potential benefits for CSS developers:
You could organize your stylesheets as a 1:1 mapping of the DOM, similar to what you see when you examine style rules in Firebug and Chrome Dev Tools. A smart editor/IDE could auto-populate styles for DOM elements with shared styles/classes. That redundancy would then, of course, be filtered out by the Specificity Filter/Optimizer.
Stylesheets could have their structure pre-populated by a tool that scans the DOM and translates it to CSS selectors/rules. This means a developer would only need to update the HTML; the CSS "tree" would be kept in sync to reflect the current state of the DOM. A smart editor would let you jump to the CSS definition for an element/class for styling -- or even make its style rules visible in a separate panel.
In a way, this almost seems like a step backward - like a feature you'd find in Dreamweaver or WebAssist to help newbs learn CSS. But the basic idea of a CSS selector optimization tool seems like a no brainer, and the type of workflow automation I've described would be the logical next step -- and the catalyst would be the Specificity Filter.
I looked into some of the better-known CSS editors and web IDEs, but haven't found anything offering this type of functionality beyond targeting a single element and generating a selector for it.
Update 2: CSS Selector Performance
In response to Spliff's comment, here are two great articles on CSS selector performance:
Performance Impact of CSS Selectors by Steve Souders
Efficiently Rendering CSS by Chris Coyier
Both agree that micro-optimizing CSS isn't worth the effort, but that over-qualified descendant selectors are "an efficiency disaster." I haven't benchmarked yet myself, but suspect that the kind of "DOM Mapping" approach I'm suggesting would cause a performance hit without an optimization step, either manual or automated.
Related Questions, Links, and Tools:
Points in CSS Specificity
Tool to See CSS Specificity
Tool for Cleaning Up CSS
Order by CSS Specificity
Top 5 Mistakes of Massive CSS
Google: Efficient CSS Selectors
Procssor
Clean CSS
CSS Tidy
You could attempt to take a different approach, try to write your selectors as small (low specificity) as possible. and only make them more specific when needed.
With that way of working you don't need a tool.
Just going to throw this out there-- it doesn't 'answer' your question,but it's a tool I like to spread the word about for people who do a lot of css programming: Firebug.
If you're not familiar with it, it's a tool for web browsers. You pull up your page once it's installed, right click and select 'Inspect Element.' It will show you all css affecting different elements on your page, and is useful for creating clean, precise css code. Also it makes it easier to see instant updates on what your page would look like with slight modifications. It will inform you of useless css code that's being overridden by other css code.
ALSO! Firebug now is available for almost all browsers. Not just Firefox. Personally, I'm partial to using it in Chrome.
We really can't do without specificity because it is the only thing that saves you when you have two or more rules colliding. Specificity brings sanity to the whole jumbled CSS rule, so it is more of a blessing than curse. Some of the stuff you talked about, like the CSS selector, can be done using Firefox/Firebug. I'm more disturbed by browser compatibility.
Actually there's a way you can do this using HTML5 and CSS3. The standard technique is to specify elements using the HTML 5 attribute "data-" and then do CSS selection for this attribute. This isn't the purpose of the attributes, but you can customly specify some elements that you can use to even switch the theme of a site.
So, for example, you can end up creating your specificity filters manually in CSS, by specifying
<b data-specificity=2>test</b>
where data-specificity only matches to parents above.
UPDATE:
Alright, so for example, let's say you have a paragraph class, but you want to specify which parent, or how many parents the paragraph can inherit properties from. You would use rules for each potential parent that can be inherited from:
p[data-specificity="1"]{
color:red;
font-family:verdana;
text-decoration:underline;
}
p[data-specificity="2"]{
color:black;
font-family:arial;
}
div.container > *[data-specificity="2"] {
font-family:impact;
color:blue;
text-decoration:underline;
}
So these rules mean that any p tag which is a direct child of the div container and has specificity 2, is allowed to inherit properties from the div container. The blue color of the div gets inherited by the p with data-specificity 2.
Here's a JSFiddle where you can see this!
The idea is that like this, using HTML5, you can control exactly which elements are allowed to inherit which properties. It's a lot of extra code to write (for both child and parent elements) but you can use this to get rid of some unnecessary specificity
I've never actually seen anyone use this method in practice, I pretty much just cooked it up for you, but I think it could be very useful, what do you think ?
Is there a performance difference between these 2 selectors assuming they match the same # of elements (a single form)?
#master .body form {}
#master form {}
I've heard that CSS selectors can make an appreciable speed difference for page rendering. I was also curious if this applies mostly to page load times or also for scenarios where you add a class to an element via JavaScript and how fast the browser can render that visual change.
interesting stuff in there:
http://calendar.perfplanet.com/2011/css-selector-performance-has-changed-for-the-better/, http://www.stevesouders.com/blog/2009/03/10/performance-impact-of-css-selectors/
Google has a plugin for Firebug/Developer Tools that analyzes your page's speed. One of its tabs is for CSS selectors. You just have to run it and it will tell you which one is better.
From what I know, by the way, the first is slower. The less elements you need to select, the better.
I am fairly new to css3 using selectors (or simple css selectors in general) and am curious about the performance comparison of these css selectors vs jquery or javascript selectors?
Say you have something like this:
css version
#someID > div:nth-child(2n) { some css .... }
jquery version (edit)
$("#someID").children(":nth-child(even)").css({ some css ....});
Is it often faster to use the css selectors whenever you can, or use jquery selectors to adjust the css involved with an element or set of elements? Mainly when the set gets rather large. I would assume there wouldn't be much performance difference with only a handful of items?
Thanks!
jQuery's selector engine shares most of the same syntax as CSS, effectively extending the selector standard. This means you can pass most valid CSS selectors (with some exceptions) to jQuery and it'll handle them just fine.
jQuery optimizes valid CSS selectors for modern browsers that support the selectors API by passing them directly to document.querySelectorAll(). This means your jQuery selector will have almost equal performance with the equivalent CSS selector, with the only overhead being the $().css() and the selectors API calls.
For browsers that don't support the selectors API, well, it's pretty obvious that jQuery will be really slow as it has to do all the heavy lifting on its own. More importantly, it will simply fail on the exceptions that I link to above as well as any other CSS selectors a browser doesn't support.
However, with all that said, jQuery will invariably be slower, as the browser has to run through a script and evaluate it before getting a chance to apply and compute your styles.
And after all this, honestly, it's not much even if you had hundreds of items — chances are the browser is going to take longer to fetch the markup than to render the styles. If you need to do styling, and CSS supports it, why not use CSS? That's why the language was created in the first place.
Pure CSS will always be faster since it's done within the browser and optimized!
The downside is that some selectors might not be supported by the browser you're on. See http://caniuse.com/#feat=css-sel3
For me if I use jquery means that I want to put some effect on it, say like
$("#someID:nth-child(even)").css({ some css ....}).fadeIn('slow');
Apart from that you better use CSS itself, but we are barely to see the difference of it anyway, at least for a small scope system.
I've found this web that compare selector capability from different javascript framework and jquery does it quite well.
javascript framework selector test