Many, but not all, HTML layout problems can be solved with CSS alone.
For those that can't, JQuery (on document load) has become very popular.*
As a result of its ease, many developers are quick to use JQuery or Javascript for layout and style — even without understanding whether or not the problem can be solved with CSS alone.
This is illustrated by responses to questions like this one.
Is this bad practice? What are the arguments for/against? Should someone who sees this in practice attempt to persuade those developers otherwise?
If so, what are the best responses to arguments in favor of JQuery saying it's "so easy"?
* Example: Layouts that wish to use vertical layout flow of some kind often run into dead ends with CSS alone — this would include layouts similar to Pinterest, though I'm not sure that's actually impossible with CSS.
2 Answers 2
If the problem can be solved using CSS, it shouldn't be solved in Javascript, and it's a definitely bad practice to do so:
- I guess no one has JS disabled nowadays, but NoScript is probably not completely negligible
- Harder to debug and maintain
- Probably will introduce a noticeable and ugly effect when JS loads and "fixes" the layout
Of course, there are things which cannot be achieved in CSS alone. In that case, of course, JS is the right solution if you strictly need it.
HTML CSS and JavaScript are a nicely bundled MVC framework. HTML is the model, all your data belongs there, with some nice hooks for the view and controller. CSS is the View, all your styles belong there, possibly with some free-floating styles that can be applied by the controller. JavaScript is the Controller, all your interactions belong there, making use of hooks into the model and view (classes & ID's).
-
That's a good principle to start with, but I'm looking for a little more... For instance, what constitutes appropriate manipulation of the view with the controller?Nicole– Nicole2011年11月22日 21:12:49 +00:00Commented Nov 22, 2011 at 21:12
-
This is not at all true. CSS does not describe the structure of the view, it only styles it. The structure of the view is your HTML; or nowadays, it's your React, which is actually JS ;)Andy– Andy2016年01月27日 10:13:00 +00:00Commented Jan 27, 2016 at 10:13
-
@Andy, you're thinking in the context of a full app. This post is discussing MVC in the context of an individual web page. A view is a description of how data (the model) should be rendered, which is exactly what CSS does. The controller changes the state of the model which then is again rendered by the view (JS). If you separate your concerns properly, keeping your styles in CSS, your interactions in JS and your data in HTML everything will be simpler.zzzzBov– zzzzBov2016年01月27日 14:27:03 +00:00Commented Jan 27, 2016 at 14:27
-
display: inline; float: left
on all of the div elements? (This is offhand, I haven't tested it)