526 points · by nvk · 13y ago · 221 comments
It feels like to me, and someone please tell me why I'm wrong, that the amount of hackery that goes into making webpages look the way web designers want them to is astounding. I google for solutions to various problems and the top rated comment on StackOverflow says "...there isn't a good way to do this in CSS, but here is this hack...".
I feel like somewhere in the universal programming ether there exists a beautiful unification of HTML, CSS, and JS that doesn't rely on any ugly hackery, and it's just waiting to be found and start a brave new world of web programming...
Sometimes I wish I could get back all the brain cells that I've wasted on the hundreds of "little tricks" you need to know to get things working -- and then working cross-browser.
Short answer: CSS is just a horribly, horribly, terribly badly designed language. It's the absolute worst. Don't let anybody tell you otherwise. It's that, it's what we've got, and it is awfully powerful in many ways. But it's complete rubbish in others, which include a lot of incredibly basic layout things.
When the committee responsible for CSS started working in the late 1990s, it seems to have lacked any members who knew anything about layout. Certainly, the browser was a new challenge, but automatic layout engines had existed for decades by that point. TeX, for example. While it is a beast, I have usually found it far easier to get its glue-and-boxes model to do what I want than wrestle with CSS.
To make matters worse, the CSS people considered it a badge of pride that CSS lacks programming features. Allow variables to represent colors so we don't have type #f0c450 all over the place? Nesting constructs? Perish the thought!! That would make it look like a programming language, with scopes! As a result, we now have LESS and Sass which plug up the worst holes, but do nothing about the fundamentally brain-damaged layout model.
For example, centering in CSS is trivial if you're only doing it for one viewport size, font, font size.
I'm talking about things like the way "floats" transformed from a way of wrapping text around pictures (good) to a general-purpose layout mechanism (disaster).
About how there's no way to put a footer at the bottom of your page that stays at the bottom if your content is short, but gets pushed down if your content is long (the normal desired use case).
About how the only way to get two columns of equal height, but that expand to fit the text, is to use a <table>, but that this is supposedly disallowed because it's "unsemantic".
About the complete disaster that float-clearing is, yet how it's central to almost all modern CSS layouts, and fixed only by bizarre byzantine hacks like "clearfix", overflow:hidden (which breaks other things), or the classic "<div style="clear:both;"></div>" which needs to be peppered throughout HTML, negating the whole supposed distinction between HTML and CSS.
And finally, the fact that the width of an element doesn't include its border and padding, making for nesting div's that include border and padding much more difficult than it should be. (Although this is, of course, fixed in newer versions of CSS.)
In the end, it's not really "current language features", but mainly the disastrous decision to adopt floats as a basic layout concept, instead of grids/columns/etc. (Which is, of course, why so many people wind up using <table> in the end, which has its own problems...)
I can tell you that I'd much rather use CSS than Android XML layouts, or WPF, or adding layout containers a la Swing or AWT. It's simple, easily understood across disciplines, and very powerful. Elements of a pretty well designed system.
On the other hand, it's 2013 and we're still trying to figure out how to center one element inside another.
In some ways, we are trying to apply desktop application design paradigms to something that started document or content oriented.
Which is exactly the problem. Web development today is a Turing tar pit, because we're using tools that were originally created for very different purposes. HTML is great for static documents, and lousy for apps. Javascript is great for attaching dynamic behavior to widgets, and lousy for large-scale software projects. CSS is great for consolidating style information, and lousy for layout. Yes, after over a decade of hacking by many smart people we've built up elaborate frameworks that sort of do what we want most of the time, but I wish we could have had more appropriate tools in the first place and been able to spend those resources elsewhere.
Flexbox isn't the answer either. I had high hopes for it and I'm in the middle of redesigning a web application UI using Flexbox for layout, and I still can't do some basic things like have an overflow:auto content area that expands to fill the space between a fixed left-hand nav panel, a variable-height fixed header, and a fixed footer. I'm still stuck with a bunch of javascript and a window.resize event handler to measure some heights and adjust the sizes of my containers. Maybe the upcoming CSS grids will work, but it'll be another couple of years before support is wide enough for me to use them.
EDIT: I also wanted to say that I've learned xaml in the past few years, and that's absolutely not the direction I'd want CSS to go.
A lot of people who are shocked with the complexity of CSS aren't saying this after switching from another better GUI environment, they're getting into visual apps after doing backed work.
CSS is not perfect but I'll take it over previous presentation idioms any day.
You're on. I pick QML.
On the contrary, it's the box model that's horribly designed. CSS is quite excellent.
We're long past the days of web pages being simple hyperlinked documents, but the browser's layout options haven't evolved quickly enough.
16. When your language is nowhere near Turing-complete, syntactic sugar can be your friend.
See this well trafficked "CSS sucks"-type article, Ctrl-F the comments for John Nagle, be tantalized at the hints of how it could be so much better: http://www.raizlabs.com/blog/2006/09/25/ten-reasons-why-css-...
Look up "constraint-based layout" and more specifically "constraint cascading style sheets". You'll find papers such as this one: http://citeseer.ist.psu.edu/viewdoc/summary?doi=10.1.1.101.4... and this one: http://csis.pace.edu/~marchese/CS835/Lec7/mmJournal.pdf thoroughly describing such a system.
Find "GSS - Grid Style Sheets" at http://gridstylesheets.org/ , "an implementation of Badros & Borning's Constraint Cascading Style Sheets". This is still half on my todo list, but it seems like the real thing. The catch? Relies on Javascript.
Dream of a world in which this kind of system was built into browsers as the primary way of doing layout <insert Simpsons happy dancing people gif here>.
It’s not that CSS is hard; it’s that CSS is bad. (...) The worst problem with DIV-based layout is that the layout system is too weak. (...) There’s no way to relate a DIV to anything but its predecessor, its parent, or an absolute position. (...) Table layouts allow table cells which span multiple rows and columns. If all tables could do were simple grids of cells, the CSS approach might make sense, but tables are more general than that.
I get it that HTML is supposed to be for content, CSS for layout and JS for programmatic logic, but the house of cards, duct tape, bailing wire and chewing gum that goes into making a web application is astonishing.
I almost think it would be easier for somebody to come up with an entirely different "web application/dynamic document layout" technology stack with a sane and well-working model all the way through, so that stupid basic things like vertical alignment don't go unfixed year after year after year and we end up with the teetering tower of hacks we have today. We pretty much know what we want out of the web, somebody should just go build it from top to bottom all over again and throw out the huge train wreck we have to deal with today. Sure it would take a while to catch on, but I bet a more efficient set of tools and display environments would rapidly catch on.
We've done it before and replaced older broken technologies with newer, why not do it again?
That is to say, it's not possible to create any conceivable layout with CSS alone. It might be possible if the thing spits out Javascript as well.
Yes, but if someone managed to create a logical, concise Web publishing standard that was something other than a can of worms, it would be a proprietary system, most likely patented. Which means no one would voluntarily adopt it.
The advantage of a public, open-source, no-one-in-charge system like we have now is that it's collaborative, democratic, and free. That's also its disadvantage.
For a classic counterexample, look at Apple's products -- they create much more consistent and usable products than the rest of the marketplace. But as many have said, Apple is a walled garden. If an Apple product happens to do what you want with no changes, then fine, otherwise you're out of luck.
Freedom is messy. Democratic technology seems always to veer toward chaos.
The W3C isn't a town hall, it's more like the UN. At best they prevent the web from going back to the chaos of the mid-90s.
It was called Flash. Or Java applets.
See history.
Edit: since you are a new developer, let me add that "ugly hackery" is what you quickly arrive at once you start doing anything of reasonable complexity (read: stuff that's actually useful). Handling the edge cases is what consumes most of the code in real production applications, and this is conveniently omitted from the beautifully clean code presented in tutorials and examples.
CSS, from my experience, makes it very easy to do web design the right way and very hard to do it any other way. It's just that the right way is often a little different from what people expect. If you accept that <i>the browser is the boss</i>, you'll be a lot happier, and incidentally your users will be a lot happier as well. The trouble is people coming from other platforms or mediums often expect 100% control, and for that it really doesn't hold your hand.
I totally agree. For example, the CSS box model sounds so simple and elegant at first, but when you add dozens of styles and elements to your page, the interaction between different styles can quickly become horribly messy no matter how disciplined you are with your CSS code. Beyond a certain number of styles, CSS inheritance turns into a black art.
CSS simply doesn't scale well for anything beyond relatively simple pages. A huge part of designing web pages is layout and spacing and yet positioning and spacing elements remains ridiculously messy and convoluted (even with CSS3).
You could also argue that tools like SASS and LESS are in effect sticking-plasters for inadequacies in CSS.
I know hindsight is a wonderful thing, but if we were designing CSS today from scratch, I think it would be designed very differently.
It seems like flex-box fixes a lot of this, but at the same time, it could be so much easier.
You're right though. CSS would be so much different and so much more gloriously painless to use. I can even imagine a better styling engine allowing for applications like macaw, dreamweaver to actually generate properly good CSS and thus building sites with a GUI would finally be plausible.
It's why it's so frustrating when people treat front-end design with disdain as something trivially easy. Of course, if you only decide to serve the newest version of Chrome and Safari, it can be easy to remember that there people out their who don't - or can't use them.
It's web development you're referring to.
Some material:
http://www.raizlabs.com/blog/2006/09/25/ten-reasons-why-css-...
The user gets what they want, the designer gets what they want, and the only people unhappy are some purists.
why? what about this is wrong?
You can get away with using "display: table-cell;" and the like inside components that are independent of responsive requirements, though.
Also remember that not everyone views the web in a browser. Having well structured markup helps those that use screen readers or alternate methods of browsing the web.
I don't think this is true any more than "good print design and good postscript go hand-in-hand".
I don't think tables are the right way either, but they're too often the pragmatic way until CSS gets dramatically more expressive.
The "restraint" you're talking about is not something designers should have to accept —- not least because CSS appears to be being developed with insufficient concern for what designers would actually like to be able to do. If it wasn't, vertical alignment would have arrived long ago.
It also makes it far harder for other user agents to make the design fit in small spaces: many table based designs are completely unusable on mobile devices for instance. While the alternative might still not look nice in such an environment, it is more likely to not be completely impractical to use.
Of course if you are presenting something that naturally fits in a tabular structure, tables are the thing to use as that is what they are designed for.
The HTML table model has evolved from studies of existing SGML tables models, the treatment of tables in common word processing packages, and looking at a wide range of tabular layout in magazines, books and other paper-based documents.[1]
It was only later when table layouts began to be discouraged.
[1] http://community.roxen.com/developers/idocs/rfc/rfc1942.html
I do agree though that it is a pain when something is easily achievable in tables but doesn't work in normal CSS. Vertical alignment being one of them.
What does annoy me is when you see people creating "CSS table" systems. I'm not being funny but that is just plain stupid. I saw a whole project dedicated to replicating the behaviour of a table.
I started developing when tables were fine to use for all layouts and I feel CSS was adopted as a layout too early without some very basic things being answered.
Unfortunately the real world hardly ever works like this.
Usually developers try to find a way to solve the problem because they are engineers and that is what engineers should do. HTML, CSS and JS wasn't invented to what it has become today. It has evolved thanks to people like you and me who has find ways to use to our advantage. Example AJAX was existed since dark ages (IE5+) but no one used/knew about it. Google used that in google maps in 2004. Now, pirates are using it in usenet/torrent applications (utorrent, sabnzbd, sickbeard etc), or 3d rendering in the cloud (http://home.lagoa.com/).
If you are waiting for something better to be found, i think you will have to wait long time. There is nothing on horizon that is as simple as HTML.
For me, hardest part is in the web development is to deal with designers and product managers.
But that's how I center every one of my "modal dialogs" on a site -- the whole modal dialog is inside a <table> with position:fixed and top/bottom/left/right:0. Then, just give the <td> a "vertical-align:middle", and then put your desired visible dialog <div> inside it.
It's annoying to have to wrap something inside of a <table><tr><td> just to vertically center something, but it sure beats using JavaScript to do it. (You might be able to do it just with the display:table-cell property too, but it's been a long time since I checked browser compatibility.)
> It's annoying to have to wrap something inside of a
> <table><tr><td> just to vertically center something
And you dont have to. Because your container does not have to be a table, and you don't need cells and rows. Just use display: (table|table-cell). See for an example: http://css-tricks.com/centering-in-the-unknown/It is not OK to use table and friends in you HTML just for styling purposes. It's totally OK to use display: table* in your CSS, because CSS has no semantics, its purpose is styling.
I keep hearing this dogma, don't use tables for layout, but nobody has ever explained to me why it is a problem in practice.
HTML is meant to be parsed and interpreted by machines too, with no visual representation. Tags are meta-data about their content. A 'table' element says "I contain tabular data", and user agents will make lots of assumptions based on that. One of the consequences of this is you'll be giving bad data to search engine bots, that's why it's bad for SEO.
HTML is also meant to be used by non-visual interpreters, like screen readers. Assistive technology is not only for the legally blind; visual impairment affects 20-30% of the world's population. We don't see high user %s because they just most won't bother, it's too hard, sites' HTML is broken, it is easier to have somebody look it up for you.
Going on a little more over semantics, there are rules for what elements can contain each other, so that a structure can be inferred based on headings and hierarchy. By not following the rules you are wreaking havoc on this, and preventing aforementioned bots and screen readers from providing meaningful navigation and context for your page.
We were supposed to have a semantic web by now, where every piece of information was annotated with meaningful meta-data, allowing for context-aware applications (add this commenter on facebook; where can I buy this product?; add this event to my calendar). Turns out it's damn hard to get everyone to use markup correctly, or even agree to common formats.
<div id="rant"> Presumably the goal is to create a strong separation between layout/design and content as HTML is want to do. However, I don't agree with the premise that design is not content even in the context of translating 'content' to different display systems including for the visually impaired. A movie cannot be automatically retargeted to a blind person by just playing the audio, you must actually do the work translating it to a different form such as a novel, or scene descriptions read aloud. Sometimes as with say a Woody Allen film, you wouldn't miss much if you could only hear it, but something like 2001 wouldn't work so well. Like it or not the internet works exactly the same way, all 'content' does.
Layout and design is content. </div>
If you are trying to provide a layout for both mobile and the desktop, putting tables in your html will definitely make it harder. If they are in the CSS, you can use two different CSS styles for mobile and desktop.
Often when I write stylesheets for a site, I like to have a default table style. Type, possibly border/spacing, padding, etc, depending on the site. Even if there are multiple visual "types" of tables to display, typically they will all have a common set of margin/padding at the least.
If you wanted to use a table for layout in a site with default table styles, you would have to have a whole set of style resets to get it back to zero layout, before adding your custom layout stuff. This is ugly, and a pain.
One point of using a div for layout style is that it is always "zeroed", and you can assume when styling one that there's nothing that needs to be overriden.
I love how your example uses 'something-semantic' as the class of the nested divs, as if labelling them semantic makes it so - this is an ugly hack around a deficiency of CSS and not far removed from using tables. It is possible to centre things vertically (with nested divs) or have several columns of freely defined height, but people have to go to extreme lengths to do so and mangle their markup in the process, because CSS is sorely lacking in some fundamental aspects of design. Things which should be simple are hard, and it's impossible to truly divorce the meaning from the form because of bugs and deficiencies in CSS, which leaves us adding nested divs all over the place to get the correct layout.
CSS should have had vertical and horizontal centring for blocks from the start, it should also have had some system of grids and columns and a concept of baselines. It's painfully clear in the design of CSS and the huge gaps in the coverage that it was an ad-hoc reaction to browser developers' problems, not to the problems of designers styling HTML. It could be radically simpler and have far more power if they went back and rethought the foundations of the box model and considered other techniques like grids which have been used for hundreds of years to present information.
Why doesnt CSS just have a property like 'placement: center middle' or something.
Of JS/DOM/CSS in HTML5, CSS is the worst standard. Depreciation is the best we can hope for. I’m sure MS and Mozilla will fight it tooth and nail, but maybe Google will pull a Dart/Go here and give us something decent to work with.
A placement: middle, without a rigidly defined height, would require the layout engine to know about document information after the element requesting a middle placement.
It would be nice to see a complete overhaul of how presentation is done, with what people have sought to do on today's web in mind.
Here's a jsfiddle to illustrate it. http://jsfiddle.net/qu5jq/
I had no idea you could use % within transforms that referred to the size of the element itself (since all other % in CSS refer to the size of a parent element).
Thanks!
I've spent hours in the past the past getting correct centring behaviour in CSS, then tried by just putting the whole thing inside <center></center> and had it work immediately in all browsers. But apparently that's "cheating".
It's the standards makers' fault. Needing to center something on either the x or y axis relative to the parent is as common a scenario as you can get.
Articles about how to do this should be summarized like this: "Vertical centering hard/hacky/messy unless you just put it in a table. So put it in a table".
(I do realize the article says this).
BTW, regarding the argument about the damage of using tables wrt screen readers, google themselves used tables to layout very basic buttons on their landing page until very recently. If you use it sparingly and just for this purpose, screen readers will do just fine. Now, using tables for other types of layout can and will break screen readers but a full old-school table-based layout is a long way from having a single TD to center stuff.
margin: auto;
position: absolute;
top: 0; left: 0; bottom: 0; right: 0;
The JavaScript console error I see is: Blocked a frame with origin "http://s.codepen.io"
from accessing a frame with origin "http://codepen.io".
Protocols, domains, and ports must match.
localStorage.keys is null, thus the page does not appear to be using localStorage.How is localStorage a significant privacy concern? My understanding is that websites only have access to the keys stored by that particular domain.
But, I can remember trying projects with tableless design at that point, and absolutely beating my head against a brick wall attempting things in CSS that required almost zero thought with tables. Then, I'd finally get it right in one browser only to find that it looked like garbage in another.
It was like having a toolbox with a hammer that I couldn't use, instead being forced to nail everything with a screwdriver. And it wasn't just that I was accustomed to tables. They were easier and more natural. When you think about it, layout is nearly always grid-like.
So, I confess that there were times when I said screw it and reverted to tables. I'd solve problems that weren't working after hours of trying with CSS in literally minutes.
And the challenge with CSS is still apparent. Here we are all of these years later, still trying to do something as simple and frequently necessary as center things vertically which, BTW, doesn't work in my stock Android browser.
CSS is a bloated, convoluted mess and just too much work for simple things. That's why I have always found it somewhat draconian that people insisted on CSS as if it didn't have its own significant issues. If there were a tag that operated just like tables, but indicated layout or, as I think someone else suggested, a simple attribute to mark a table as layout vs row/column data, most of the semantic/SEO problems could be solved.
For that matter, I am not convinced that we should be so bent on having html pull double duty as the source for semantic data and the source for a presentation engine's rendering. Maybe a different approach altogether could be more liberating and efficient on both fronts.
Not sure exactly what you mean here. Are you talking about floating divs to wrap elements to the next visual "row" for smaller screen sizes, as in responsive design?
Because I don't find this necessary very often in practice, and certainly not nearly as often as the tons of other general layout that's required. Not to mention, of course, that you can still use divs where "needed".
BTW, on a side note, the jury is still out on responsive design for me. Or, at least as I have frequently seen it practiced today. For instance, many times a site with sidebars (including nav) will wrap the sidebars on smaller displays such that content, nav, etc. are all lined up in one vertical column. Not very appealing or usable IMO.
I really believe that how we treat designing to different formats will change and this responsive wave will pass. And, while I know there are other reasons to wrap elements, I do think responsive design is responsible for a good bit of it.
http://www.imgur.com/7JA69Ty.png
Or is the browser chrome considered usable real estate.
You can also do this
position: relative; margin-top: 50%; transform: translateY(-50%);
But overall your point is fair: HN has a lot of people (including me) with weak front-end skills.
If IE8 and down matters, then there are polyfills available for this functionality.
Making any layouts and god forbid centering elements has always been a headache for me. Even by looking at the CSS examples provided by the link my first thought is how random they all seem and how ugly they are not to mention difficult to remember and use. There should be a single way to center an element. It should be an obvious operation given how important and common it is.
Some very useful CSS properties might take a lot of code and be hard to implement in native GUI toolkits like floats, overflow, height/width with percents, text wrapping etc. This is a sweet spot where HTML/CSS shines.
I have been playing with QML lately and decided to implement the Dialog (Absolute center within viewport) that pops after visiting the linked page just for comparison:
Here's the dialog equivalent that just fills the entire screen of an application done with QtQuick 2.0 for Desktop.
Layouting is easily done by anchors. Filling a rectangle to match a parent's container, centering an element inside a parent, etc. Other containers such as Rows, Columns or Grids are also provided. Property bindings are used for centering the dialog even if the viewport changes. Text wrapping is also done explicitly and binding was necessary to limit text width to the ScrollView for it to work.
One big difference compared to CSS is that by looking at the source I can see at glance what the layout structure is and what might be happening with the element.
Another cool thing about QML is that it's as simple as taking the code, creating a new file 'Dialog.qml', adding a few properties, a signal and some functions and we get a reusable standalone component:
that is very convinient to use:
result: http://i.minus.com/iGTQhAxP55bBP.gif (3MB gif)
http://jsbin.com/ezocec/1/edit (25 lines counting the HTML)
CSS has columns and grids, custom text wrapping. These features are available now in >90% of browsers. The `.dialog` class can be used as component without any changes, and we have things like component.io and browserify to package them up with behaviour.
result: http://cl.ly/2w1o3h0i1t0r
Perhaps a tool can bundle resources, but in the end it's still going to be inserted into the DOM and can potentially clash with other code since everything lives in a global namespace. There's also the problem of competing tools and the dilemma of which one to choose. Any other additional library that is meant to augment/fix HTML/CSS is another dependency that can cause problems and needs to be maintained.
QML is meant to be extensive. Not happy with how the drop shadow works? Write your own shader that does it the way you want it. Feeling that there's some primitive like an Ellipse missing? You can write your own in C++ and expose it to QML easily. In fact you can expose any native code to QML.
With HTML/CSS you are constrained to the environment it works in.
QML supports components, animations, transitions, particles, states, bindings, i18n and much more. It's also very smooth, qml is hardware accelerated. In the case of CSS so you get some hardware acceleration only for animating properties like translation, etc.
Here's the dialog I posted before which I changed to support states and transitions and also added an inline shader and particle emitter:
http://i.minus.com/iATg82IRCaMa9.gif (result 4MB gif)
As it can be seen it's highly declarative and it basically contains no javascript logic at all besides setting the states.
Of course a lot of such features are available indirectly in HTML/CSS by piggybacking on third party libraries/frameworks, but wouldn't HTML be so much nicer if it were designed with those things in mind from the very beginning?
Shadow DOM is the specification that will fix the collision/cascading issue, making it possible to isolate components. You can now write your own shaders, use custom masks/clipping etc, and of course, SVG for unlimited vector shapes. If that's not enough, write your own graphics layer with WebGL or Canvas.
http://jsbin.com/ezocec/3/edit
Now around ~80% less code.
This is a fun but pointless showdown of course, these are technologies born worlds apart, with different audiences, purposes and constraints. HTML appeared in 1990, with the sole purpose of marking up hypertext, grew organically and has a hundred other interoperability concerns; QML showed up in 2009 (?), twenty years later, and was designed to solve specific problems. I'm certain the web wouldn't have grown as fast if it didn't have a stack as accessible as html/css.
Details: http://jsfiddle.net/uy64k/6/
This requires no extra markup, but it does require the font-size and line-height to be reset.
[1] http://stackoverflow.com/questions/5009864/using-all-four-po...
If I recall correctly, the original Mac UI guidelines specified that the midpoint of the box should be 1/3 the distance from the top.
Other than that, I'd say that doing this kind of stuff in CSS would by default be much faster in a web page context.
ps. I didn't mean pure javascript solution anyway:)
[1] http://caniuse.com/flexbox - it's in the current version of all browsers (some still prefixed).
I've got to enable assets. and s.codepen.io to see the page rendered.
That appears to be due to the use of an iframe from s.codepen.io for the content.
These have intrinsically sized (autosized) boxes that vertically and horizontally center in some container.