Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I'm working on a responsive design would like to know if it is better to style an element using JavaScript or with CSS? CSS is certainly easier to maintain, I won't argue that, but I'm a lot more comfortable building an object in JavaScript. Maybe I'm making more work for myself than I should, but I feel like I have more control overall and I like being able to hook into every object on the screen.
I have constructors that generate the entire page layout and push it into the DOM. No images, just pure JavaScript styling and SVG icons.
What I would like to know is:
What performs better?
What, if any hardware support is there for JS or CSS?
Is a pure JavaScript solution better than using CSS Calc()?
What's more portable?
What's more forward compatible?
I tend to avoid jQuery as I'm more interested in learning what makes things work right now, so pure JavaScript and CSS3 only, please.
Your styling should be done using CSS wherever possible. Have different classes setup according to your needs, then add or remove classes when absolutely necessary with JS.
One thing to keep in mind is that changing styling via JS is a one-time change. Elements added dynamically VIA Ajax won't inherit the styling changes automatically. Another good reason to stick with CSS.
See this post for additional confirmation Should I load responsive design via JS or CSS
As suggested in the link
Putting everything regarding styles in the CSS files is the best
practice.
HTML => Structure
CSS => Styles
JS => Logic
CSS is the best way to style an (X)HTML document.
Even if you need to style a document by using raw JavaScript or DOM, or some framework like jQuery, it'll mean you're giving values to CSS rules.
The rule should be:
Use pure CSS when you can style a predictable document - also you can
enhance your CSS and use CSS selectors for generalized or complex
scenarios -.
Use JavaScript/DOM or frameworks like JavaScript when document or portions of it aren't predictable or are created on-the-fly and
you're applying special effects like fades or any other - in fact,
CSS 3.0 has transitions so it's possible to do a lot of things
without JavaScript -.
After all, think how simpler can be things done with CSS and what kind of overkill is using JavaScript instead, and keep in mind its cons (a very important point: browser compatibility and performance).
The more CSS you use, the more standarized, cross-browser, performant and maintainable web.
UI should be left to UI solutions (HTML/CSS). JavaScript should only provide additional functionality.
To supplement this (because you mention CSS3) if you're referring to animations and new additions to CSS3 (that may not otherwise be available) you can use javascript--but only as a fallback. (e.g. using jQuery's fadeTo over creating an animation timeline with CSS3).
There are serious drawbacks when applying styles with JavaScript, not only because you have no control over specificity, it is slow (as you'd expect), any .css() calls involving classes, e.g. $('.something').css(...), will apply css to only elements of that class that exist at the time, not .somethings created in the future.
Related
I'm developing a jquery plugin today, and I found it is impossible to apply two css files without overlapping each other. In other words, the new plugin will destroy the original layout. Is there any way to make a plugin running in a dividual environment?
You may rebuild the original css code to clear the overlapping by more strict rules, or, you may want to switch the plugins you are using right now to different.
Another thing you could do is change the source code of the plugin.
You should avoid overwriting existing CSS without knowing what it could do. Try to add bit by bit of the CSS code to check which code does affect the original CSS. The bottom CSS will always overwrite top CSS.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I'm looking to use something like Twitter's bootstrap to help me ease some of the pains of creating and working with some of the common design issues. However, I still fully intend to do a whole bunch of styling and stuff outside of their prepared stuff.
Would this be a bad idea? Potential conflicts down the road? Should I try to build on top of and use bootstrap as much as possible?
twitter bootstrap is great to get started and its exactly what it intends on helping developers. Instead of creating a lot of stuff from scratch, you got pretty much everything you need for a basic-to-medium frontend so you don't have to worry about it.
As you build your application, there will be times where you would need, for example, to replace the color of the buttons. So instead of having a .btn-primary be blue you want it pink.
you can override the .btn-primary in your own css, or even better, see how it behaves, copy the styles, change what you need and use your .pink-btn-primary.
Little by little your css would stop being twitter bootstrap and become your own variation, with the ability to rely on features being added to bootstrap with time.
Relying on bootstrap has a bit of a shortcoming - if a bug is fix or a new version changes its behavior (rare on css, but very possible on js) you will have to adjust to make sure you get the behavior that you want.
Also, You should be careful, as suggested, not to use their class names, and make sure you load your css files after bootstrap files.
good luck.
Bootstrap is meant to be used to build on top of and overwrite so you get the design you want.
As always, using Bootstrap depends on the project.
It makes starting out very easy but like most frameworks you don't always want to go against them, so you have to take them into consideration in the early stages of your design. Bootstrap relies heavily on wrapper elements and classes so using it for an existing website where the markup can't be changed won't work out for you.
Example: Their grid system works really well for their fluid container layouts but the default is 12 columns and you will want to look at all their customisation options to change this.. or see examples of using the .less pre-processor with Bootstrap and these settings apply a set margin that may not always work out for you, and you have to start thinking differently.. such as how you can nest elements to achieve the design you want, or start testing with new overwritten margin sizes.
You also need to consider any other frameworks you may be building on, e.g. ASP.NET MVC has a lot of built in features such as the client validation, and HTML helpers for form elements.. but they don't always allow you to apply wrapper elements and class names to them unless you first right your own extension of them.
Bootstrap has an Apache v2.0 license which says
irrevocable copyright license to reproduce, prepare Derivative Works
of
so as long as you keep the copyright license they allow you to change bootstrap as you see fit, obviously you shouldn't look to change what they have already extensively tested for you and you would rather just overwrite some things, but the option is always there.
I think most developers do not just use the prepared stuff, they always add some customization on top of it. As for CSS styling, You can keep the bootstrap.min.css file intact and write your custom css on another CSS file. If Bootstrap updates in future you can just replace that original bootstrap.min.css file and maybe have to make some minor adjustments.
Many people today use Google Closure Compiler to actually "compile" their JavaScript code. The advanced mode enables it to rewrite JS to better, faster and smaller JS-code that functions the same way as the original input.
Are there any good compilers out there for HTML/CSS? It could for example compress the CSS classes like a JS-compresser does. It could remove any divs (display: none;) that no JavaScript actually displays (display: block;). It could remove whitespaces. It could combine small images into sprites. It could combine files that are included on all pages into one file.
The list just goes on and on. Do you know about any good tools for this job? (Even if it only can compress CSS classes etc.)
Concatenate your css files and you made most of the work : the cost is mostly related to the number of requests.
But for removing useless rules, there is no point in using a tool : needing one would mean you don't really understand which ones are needed and why. In other words your code is a mess you must fix because at this point it may only grow explosively.
That's the same for sprites and other optimizations : only by knowing the use flow of the application, if people come back and have some images cached, or only the ones of the main page, etc. can you know what strategy to use, even if it's almost always useful to merge all your small images of one page in a big one.
No actual compilers as such that I know of, but there are tools to help you create clean html and css.
For css there is, for example, less which is a good tool for generating nice clean cross-browser markup but you have to use it from the get-go. Similarly for html, there are a few markup frameworks that can simplify generation of clean html. markdown is one such that is quite popular.
I'm working on a large JavaScript-heavy app. Several pieces of JavaScript have some related CSS rules. Our current practice is for each JavaScript file to have an optional related CSS file, like so:
MyComponent.js // Adds CSS class "my-comp" to div
MyComponent.css // Defines .my-comp { color: green }
This way I know that all CSS related to MyComponent.js will be in MyComponent.css.
But the thing is, I all too often have very little CSS in those files. And all too often I feel that it's too much effort to create a whole file to just contain few lines of CSS - it would be easier to just hardcode the styles inside JavaScript. But this would be the path to the dark side...
Lately I've been thinking of embedding the CSS directly inside JavaScript - so it could still be extracted in the build process and merged into one large CSS file. This way I wouldn't have to create a new file for every little CSS-piece. Additionally when I move/rename/delete the JavaScript file I don't have to additionally move/rename/delete the CSS file.
But how to embed CSS inside JavaScript? In most other languages I would just use string, but JavaScript has some issues with multiline strings. The following looks IMHO quite ugly:
Page.addCSS("\
.my-comp > p {\
font-weight: bold;\
color: green;\
}\
");
What other practices have you for keeping your JavaScript and CSS in sync?
My perspective on CSS files is that they describe rules that define the theme of an application. Best practices generally state that content, presentation, and behavior should be kept separate so that it is relatively easy to change that theme. By having multiple CSS files, this becomes slightly more difficult, as a designer would have more files to deal with.
Additionally, CSS (Cascading StyleSheets) rules are affected by their position in the CSS document. By having multiple CSS files with different rules in each, it may become more difficult to prioritize which rules take precedence.
Finally, if you want to find out what CSS selector in your JS file matches what CSS file, try using a cool search tool, like grep, if you're on linux. If you're using a good IDE, you can also use it to quickly search for the rules, then you can just jump to the line number. I really see no advantage in keeping the CSS rules in different files; it will only complicate matters.
Additionally, I would advise against the idea of putting the CSS inline. By doing this, you will inevitably make it more difficult for your web designer to quickly and easily swap out the styles. The whole point of external CSS is so your web designer can change the theme or provide multiple themes for different users. If you embed the CSS in the JavaScript or HTML, you've then tightly coupled the content, behavior, and presentation.
Best practices generally suggest keeping content, behavior, and presentation separate for this very purpose.
Having one CSS file per JS file seems a good thing for me. It's clean, and easy to understand and to maintain. The only problem would be to have dozens of CSS files on every page, but I suppose you combine those files to one big file, so this problem does not exist in your case.
How to embed CSS in JavaScript? It depends on the environment you have, and how the build process is done. The easiest thing is to have a large comment at the beginning of every JavaScript file, something like this:
// <...>Your copyright notice here</...>
// <css>
/*
body{color:red;}
div{border:solid 10px lime;}
// ... other ugly styles.
*/
// </css>
Then during the build, you have to search for <css>...</css> blocks and extract the CSS by trimming the /* and */.
Of course, it creates a problem: if you are using an IDE with auto-completion, embedding CSS into a JavaScript file will make it impossible to use auto-completion in this case.
My preferred method is to keep all the CSS files separate and then have a build process that compiles them into a larger CSS file on deployment.
I would avoid merging your JS with your CSS. It may sound like a cleaner solution from the file-level, I think it'll get messy fast. That, and you'll lose the highlighting and syntax assistance your editor gives you.
Check out Csster. I wrote it to solve just this problem.
You embed your CSS rules directly in your Javascript, using Javascript object literal syntax. It's no uglier than raw CSS.
Csster.style({
h1: {
fontSize: 18,
color: 'red'
}
});
The rules are inserted into the DOM on the client side. This architecture simplifies your build process and reduces client requests.
You can use it like you describe, but Csster also provides a couple other niceties:
nesting to DRY up stylesheets
color functions like darken and saturate
built-in macros for common CSS idioms like clearfix, rounded corners, drop shadows.
extension points for custom behavior or cross-browser support
It's well tested and I've used it on quite a few projects. It is independent of jQuery, but plays well with it.
I'd love to have more people use it and provide feedback.
Say you've got a menu that toggles open and closed with a button. My standard way of going about this would be to write the CSS for a closed menu, and write Javascript that specifies (or animates to) an open menu state.
Lately I've gotten into Active.js, a client-side MVC framework. It provides for view classes with builders for making DOM fragments, and those fragments can be given methods that handle things like animation and DOM state.
Something feels wonky about describing the initial state in CSS, and then describing alternate states in JavaScript. Without animation, it would be sensible to just do it all in CSS and just use javascript to add or remove DOM classes.
My other idea is to describe all of the states (folded, unfolded, red, green) of a DOM object in JSON (rather than CSS) and give my ActionView object methods for animating between those states. Is anybody doing this? Other ideas?
As far as animation goes, it wouldn't be a violation of DRY to have basic styling in CSS and then the animation or styling you can't achieve in pure CSS in javascript because you still don't have any repetition if done right. If you think its a more "pure" way to do things you can try to keep more of the styling in javascript or CSS, but those are just the languages you are using and if you consider them both expressions of the same underlying DOM its entirely appropriate to use the more expressive or compatible language wherever needed.
I typically take CSS as far as it will go and then start using jQuery to do the things that CSS can't handle or are not cross browser, like animations.